简体   繁体   English

异步调用如何知道何时在新线程中开始完成事件或使用调用者线程

[英]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. 在客户端上,它将生成DoWorkCompletedDoWorkAsync方法。

This is my observation if you call DoWorkAsync from UI thread, DoWorkCompleted will be executed on UI thread as expected. 这是我的观察,如果您从UI线程调用DoWorkAsyncDoWorkCompleted按预期在UI线程上执行DoWorkCompleted

But if I start BackgroundWorker and call service DoWorkAsync from it then DoWorkCompleted is executed on new thread other than caller thread. 但是,如果我启动BackgroundWorkerDoWorkAsync调用服务DoWorkAsync ,则在调用者线程以外的新线程上执行DoWorkCompleted Example: 例:

  1. Start BackgroundWorker instance <- From UI Thread 从UI线程启动BackgroundWorker实例<-
  2. Worker DoWork method gets executed <- Thread 2 Worker DoWork方法被执行<-线程2
  3. Call to service DoWorkAsync from worker DoWork <- From thread 2 从工作程序DoWork <-从线程2调用服务DoWorkAsync
  4. Service runs and DoWorkCompleted gets executed <-- Thread 3 服务运行并执行DoWorkCompleted <-线程3
  5. Worker 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM