ContinueWith a Task on the Main thread

Deadly 提交于 2019-12-31 00:51:02

问题


Forgive me if this is a simple question; I couldn't phrase it in a generic enough way to search for the answer.

Consider this code:

var task = Task.Factory.StartNew(() => Whatever());  
task.ContinueWith(Callback, TaskScheduler.FromCurrentSynchronizationContext())

How exactly is it determined when the callback method will execute?

Will it wait until the main thread is currently finished doing whatever it is doing, or will it get called immediately after the asynchronous call is complete? And will this callback execute entirely before the main thread returns to whatever it was doing before?


回答1:


Will it wait until the main thread is currently finished doing whatever it is doing, or will it get called immediately after the asynchronous call is complete?

When the asynchronous call completes, the continuation will be scheduled. The effect of that scheduling depends on the scheduler (of course) but for a "normal" WPF or Windows Forms message loop, I'd expect it to be scheduled in a similar way to a call to Control.BeginInvoke or Dispatcher.BeginInvoke - in other words, when the "main" thread has finished the rest of the tasks which had been scheduled before this one.

I wouldn't expect the main thread to magically stop what it's doing and execute the continuation. It could make the continuation a high-priority task in its queue, however.



来源:https://stackoverflow.com/questions/11397163/continuewith-a-task-on-the-main-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!