C# 在VSTO中使用async/await时跨线程操作无效

C# 在VSTO中使用async/await时跨线程操作无效,c#,multithreading,asynchronous,async-await,vsto,C#,Multithreading,Asynchronous,Async Await,Vsto,我得到一份工作 跨线程操作无效 。。。错误代码如下。我以为async/await会解决这个问题,但显然不是。奇怪的是,当我注释掉textBoxUser.Enabled=false时,错误消失了。想法 private async void buttonPopulate_Click(object sender, EventArgs e) { textBoxUser.Enabled = false; await Populate(); textBoxUser.Ena

我得到一份工作

跨线程操作无效

。。。错误代码如下。我以为async/await会解决这个问题,但显然不是。奇怪的是,当我注释掉
textBoxUser.Enabled=false时,错误消失了。想法

private async void buttonPopulate_Click(object sender, EventArgs e)
{
     textBoxUser.Enabled = false;

     await Populate(); 

     textBoxUser.Enabled = true; //error here
}

您的问题可能是由于VSTO未正确提供
SynchronizationContext
;这是Office插件系统长期存在的问题。您可以通过检查事件处理程序开头的
SynchronizationContext.Current
的值来验证这一点;如果为
null
,则问题是由VSTO引起的

要解决此问题,可以在任何
async void
事件处理程序的开头执行此操作:

SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());

您正在尝试从其他线程访问GUI元素。您需要调用。
private async void按钮填充\u单击
如果WinForms正在调用此事件处理程序,您应该在WinForms同步上下文中,并在主线程上继续。您是自己调用此方法还是从计时器调用此方法,还是实际调用
await Populate().ConfigureAwait(false)?@MongZhu问题稍有不同,上面的答案已过期,请发布填充代码,因为可能存在问题。2-将获得异常的行张贴到哪里。填充
做什么?你能用英语重新解释一下吗?