[英]How does async call knows when to start completed event in new thread or use caller thread
Let's say we have a service TestService
with DoWork
method. 假设我们有一个带有DoWork
方法的TestService
服务。 On the client, it will generate DoWorkCompleted
and DoWorkAsync
methods. 在客户端上,它将生成DoWorkCompleted
和DoWorkAsync
方法。
This is my observation if you call DoWorkAsync
from UI thread, DoWorkCompleted
will be executed on UI thread as expected. 这是我的观察,如果您从UI线程调用DoWorkAsync
, DoWorkCompleted
按预期在UI线程上执行DoWorkCompleted
。
But if I start BackgroundWorker
and call service DoWorkAsync
from it then DoWorkCompleted
is executed on new thread other than caller thread. 但是,如果我启动BackgroundWorker
并DoWorkAsync
调用服务DoWorkAsync
,则在调用者线程以外的新线程上执行DoWorkCompleted
。 Example: 例:
BackgroundWorker
instance <- From UI Thread 从UI线程启动BackgroundWorker
实例<- DoWork
method gets executed <- Thread 2 Worker DoWork
方法被执行<-线程2 DoWorkAsync
from worker DoWork
<- From thread 2 从工作程序DoWork
<-从线程2调用服务DoWorkAsync
DoWorkCompleted
gets executed <-- Thread 3 服务运行并执行DoWorkCompleted
<-线程3 DoWorkCompleted
gets executed <- UI thread 工人DoWorkCompleted
被执行< DoWorkCompleted
线程 How does Service client know when to start new thread and when to post it back to caller thread? 服务客户端如何知道何时启动新线程以及何时将其发布回调用者线程?
This has to do with the availability of a SynchronizationContext
on the thread. 这与线程上SynchronizationContext
的可用性有关。 In Windows Forms, I assume Silverlight is the same, when you start an application the main thread that will become the UI thread is provided with a SynchronizationContext
that allows calls to be marshaled back to the UI thread. 在Windows窗体中,我假设Silverlight是相同的,当您启动应用程序时,将成为UI线程的主线程具有SynchronizationContext
,该上下文允许将调用重新编组回UI线程。
In your first scenario, since you call DoWorkAsync
from a thread with a synchronization context available the DoWorkCompleted
is marshaled back to the initial thread. 在第一种情况下,由于您从具有可用同步上下文的线程中调用DoWorkAsync
,因此DoWorkCompleted
被封送回初始线程。
In your second scenario you are on a thread pool thread without a synchronization context so the DoWorkCompleted
is not marshaled back to the initial thread. 在第二种情况下,您处于没有同步上下文的线程池线程中,因此不会将DoWorkCompleted
编组回初始线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.