如何获取使用SynchronizationContext的任务?以及如何的SynchronizationContext还是使用? [英] How to get a Task that uses SynchronizationContext? And how are SynchronizationContext used anyway?
问题描述
我仍然在学习整个任务概念和TPL。从我目前的理解,SynchronizationContext的功能(如present)是由用于等待
来调度任务的地方。在另一方面,在工作
类的功能不使用的背景下,对吧?
因此,例如 Task.Run(...)
将总调度线程池的工作线程的行动,并忽略的SynchronizationContext .Current
完全。 Foobar的等待()
将使用上下文中的后执行生成的任务的await
?
如果这是真的,我的问题是:我如何获得工作
,实际运行操作,但使用时分派 SynchronizationContext.Current 。发送/发表
?
和任何人都可以推荐一个好引入的SynchronizationContext
,尤其是当以及他们如何被框架的其他部分所用?该 MSDN 似乎很沉默的类。前谷歌命中(<一个href=\"http://www.$c$cproject.com/Articles/14265/The-NET-Framework-s-New-SynchronizationContext-Cla\">here和<一个href=\"http://www.$c$cproject.com/Articles/31971/Understanding-SynchronizationContext-Part-I\">here)似乎是针对Windows窗体仅调度。斯蒂芬·克利里写道:文章这是很好的学习什么情况下已经存在,它们是如何工作的,但我缺乏的地方,当他们实际使用和理解。</ p>
我怎样才能获得一个任务,实际运行操作,但使用时分派
SynchronizationContext.Current.Send /后?
块引用>使用特殊的任务调度程序:
Task.Factory.StartNew(
()=&GT; {} //这将使用当前同步上下文
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
和任何人都可以推荐一个好引入的SynchronizationContext
块引用>看文章的这是所有关于SynchronizationContext的的通过斯蒂芬·克利里。
I am still learning the whole Task-concept and TPL. From my current understanding, the SynchronizationContext functions (if present) are used by
await
to dispatch the Task "somewhere". On the other hand, the functions in theTask
class do not use the context, right?So for example
Task.Run(...)
will always dispatch the action on an worker thread of the thread pool and ignore theSynchronizationContext.Current
completely.await Foobar()
would use the context to execute the generated task after theawait
?If that is true, my question is: How can I obtain a
Task
, that actually runs an action but is dispatched usingSynchronizationContext.Current.Send/Post
?And can anyone recommend a good introduction into
SynchronizationContext
, especially when and how they are used by the rest of the framework? The MSDN seems to be very quiet about the class. The top Google hits (here and here) seem to be tailored to Windows Forms dispatching only. Stephen Cleary wrote an article which is nice to learn what contexts already exist and how they work, but I lack understanding of where and when they are actually used.解决方案How can I obtain a Task, that actually runs an action but is dispatched using SynchronizationContext.Current.Send/Post?
Use special task scheduler:
Task.Factory.StartNew( () => {}, // this will use current synchronization context CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
And can anyone recommend a good introduction into SynchronizationContext
Look at the article It's All About the SynchronizationContext by Stephen Cleary.
这篇关于如何获取使用SynchronizationContext的任务?以及如何的SynchronizationContext还是使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!