[英]How can I get the continuation after an await to execute on the same thread?
As I recently discovered to my cost, doing an await
when there's no synchronization context may result in the code after the await being executed on a different thread. 正如我最近发现的那样,在没有同步上下文的情况下进行await
可能会导致在等待在不同线程上执行之后的代码。
I'm currently having problems with strange behaviour in a VSTO office add-in, which I think is possibly a result of this behaviour. 我目前在VSTO办公室加载项中遇到奇怪的行为问题,我认为这可能是这种行为的结果。 When processing events raised by the Office application, there's no synchronization context in place (unless I create a form, which will create a synchronization context). 处理Office应用程序引发的事件时,没有适当的同步上下文(除非我创建一个表单,它将创建一个同步上下文)。
My question is whether creating a form is the best / most efficient way to ensure that I have a synchronization context, or whether there's a simpler way to do it. 我的问题是,创建表单是确保我有同步上下文的最佳/最有效的方法,还是有一种更简单的方法。
Office apps do invoke their events in an STA context, but they do not provide an appropriate SynchronizationContext
. Office应用程序确实在STA上下文中调用它们的事件,但它们不提供适当的SynchronizationContext
。
The easiest way to work around this is explained on my blog in SynchronizationContext
Odds and Ends , where I briefly describe a couple of miscellaneous things that I found while doing research for my article but just weren't important enough to include. 解决这个问题的最简单的解决方法是在我的SynchronizationContext
文本中讨论 ,其中我简要介绍了我在为文章进行研究时发现的一些杂项,但这些内容并不重要。 To fix this problem, at the beginning of every event, do this: 要解决此问题,请在每个事件开始时执行以下操作:
SynchronizationContext.SetSynchronizationContext(
new WindowsFormsSynchronizationContext());
Any await
s after that should resume on the STA thread. 任何await
s之后应该在STA线程上恢复。
You might want to check out this article , which describes how to set up a SynchronizationContext without a message pump. 您可能希望查看本文 ,其中介绍了如何在没有消息泵的情况下设置SynchronizationContext。 Note that this is really only useful if you expect to have other work that you intend to await (queuing up multiple callbacks.) If you only ever await one thing at a time, your code might as well just run synchronously, since you don't have anything else to do with your idle time, like run a message pump. 请注意,这实际上只有在您希望等待其他工作时才会有用(排队多次回调。)如果您一次只等待一件事,您的代码也可能只是同步运行,因为您不要与你的空闲时间有任何关系,比如运行消息泵。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.