如何获取使用 SynchronizationContext 的任务?以及如何使用 SynchronizationContext 呢? [英] How to get a Task that uses SynchronizationContext? And how are SynchronizationContext used anyway?
问题描述
我仍在学习整个任务概念和 TPL.根据我目前的理解,await
使用 SynchronizationContext 函数(如果存在)来分派任务某处".另一方面,Task
类中的函数不使用上下文,对吗?
因此例如 Task.Run(...)
将始终在线程池的工作线程上分派操作并完全忽略 SynchronizationContext.Current
.await Foobar()
会在 await
?
如果这是真的,我的问题是:我怎样才能获得一个 Task
,它实际上运行一个动作,但使用 SynchronizationContext.Current.Send/Post
分派?
谁能推荐一个很好的 SynchronizationContext
介绍,尤其是框架的其余部分何时以及如何使用它们?MSDN 似乎对这个课程非常安静.Google 热门点击(此处和此处) 似乎仅适用于 Windows 窗体调度.Stephen Cleary 写了一篇文章,很高兴了解哪些上下文已经存在以及它们是如何工作的,但我对它们的实际使用地点和时间缺乏了解.
我怎样才能获得一个任务,它实际运行一个动作但使用SynchronizationContext.Current.Send/Post?
使用特殊的任务调度器:
Task.Factory.StartNew(() =>{},//这将使用当前同步上下文CancellationToken.None,TaskCreationOptions.None,TaskScheduler.FromCurrentSynchronizationContext());
<块引用>
谁能推荐一篇关于 SynchronizationContext 的好介绍
查看文章都是关于 SynchronizationContext 作者:Stephen Cleary.
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 the Task
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 the SynchronizationContext.Current
completely. await Foobar()
would use the context to execute the generated task after the await
?
If that is true, my question is: How can I obtain a Task
, that actually runs an action but is dispatched using SynchronizationContext.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屋!