ContinueWith在主线程任务 [英] ContinueWith a Task on the Main thread

查看:704
本文介绍了ContinueWith在主线程任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原谅我,如果这是一个简单的问题;我不能句话在一个通用的足够的方法来搜索答案



考虑以下代码:

  VAR任务= Task.Factory.StartNew(()=>无论()); 
task.ContinueWith(回调,TaskScheduler.FromCurrentSynchronizationContext())



究竟它是如何确定的当回调方法将执行?



它会等待,直到主线程当前做完不管它是干什么的,还是会被调用后立即异步调用完成?并将此回调主线程返回到不管它在做之前,之前完全执行呢?


解决方案

它会等待,直到主线程当前做完不管它是干什么的,还是会得到马上叫异步调用完成后?




当异步调用完成,延续会的计划的。该计划的效果取决于调度程序(当然),但正常或WPF Windows窗体消息循环,我希望它以类似的方式安排对控制通话。 BeginInvoke的 Dispatcher.BeginInvoke - 换句话说,当主线程完成落实已经被这个计划之前的剩余任务



我不希望主线程神奇阻止它在做什么,并执行的延续。它的可能的使延续其队列中高优先级的任务,但是。


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?

解决方案

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.

这篇关于ContinueWith在主线程任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆