Tag: synchronizationcontext

为什么每个Dispatcher.BeginInvoke回调都有一个唯一的同步上下文?

我刚刚注意到,使用.NET 4.5,每个Dispatcher.BeginInvoke / InvokeAsync回调都在其自己非常独特的同步上下文( DispatcherSynchronizationContext一个实例)上执行。 这种变化背后的原因是什么? 以下简单的WPF应用程序说明了这一点: using System; using System.Diagnostics; using System.Threading; using System.Windows; using System.Windows.Threading; namespace WpfApplication { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Action test = null; var i = 0; test = () => { var sc = SynchronizationContext.Current; Dispatcher.CurrentDispatcher.InvokeAsync(() => { Debug.Print(“same context #” + […]

如何获取使用SynchronizationContext的任务? 那么SynchronizationContext是如何使用的呢?

我还在学习整个任务概念和TPL。 根据我目前的理解, await使用SynchronizationContext函数(如果存在)来“调用”任务“某处”。 另一方面, Task类中的函数不使用上下文,对吧? 因此,例如, Task.Run(…)将始终在线程池的工作线程上调度操作,并完全忽略SynchronizationContext.Current 。 await Foobar()会在await之后使用上下文来执行生成的任务吗? 如果这是真的,我的问题是:我如何获得一个实际运行动作但使用SynchronizationContext.Current.Send/Post调度的Task ? 任何人都可以推荐对SynchronizationContext一个很好的介绍,特别是在框架的其余部分何时以及如何使用它们的时候? MSDN似乎对这堂课非常安静。 顶级Google点击( 此处和此处 )似乎仅适用于Windows Forms调度。 Stephen Cleary撰写了一篇文章 ,很好地了解了已经存在的背景以及它们是如何工作的,但是我不了解实际使用它们的位置和时间。

在主UI线程的Continuation中,SynchronizationContext.Current为null

我一直在尝试在Winforms应用程序中追踪以下问题: SynchronizationContext.Current在任务的继续(即.ContinueWith )中为空,它在主线程上运行(我希望当前的同步上下文是System.Windows.Forms.WindowsFormsSynchronizationContext )。 以下是演示此问题的Winforms代码: using System; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); TaskScheduler ts = TaskScheduler.FromCurrentSynchronizationContext(); // Get the UI task scheduler // This line is required to see the issue (Removing this causes the problem to go away), since […]