Task.ContinueWith(...,TaskScheduler.FromCurrentSynchronizationContext())在UI线程上运行的任何场景?

ang*_*son 9 c# multithreading task synchronizationcontext

我们正在观察一些奇怪的东西,代码如下:

var task = new Task(...); // run in the background, do something lengthy work
task.ContinueWith(..., TaskScheduler.FromCurrentSynchronizationContext());
task.Start();
Run Code Online (Sandbox Code Playgroud)

第二个任务调用一个事件,然后尝试更新GUI,我们得到了可怕的跨线程异常.

Thread.CurrentThread.ManagedThreadId从第二个任务中的方法检查表明它实际上没有在UI线程上运行.

这催生了任务的代码是在UI线程上运行.

有什么情况会出错吗?

Mat*_*ith 4

假设您正在使用 .NET 4.0,存在一个错误,System.Threading.SynchronizationContext.Current主线程上的 可能会变为 null,并且您会遇到此问题。如果您可以轻松地重现该问题,那么首先要检查的是SynchronizationContext.Current当您调用 时是否为 null TaskScheduler.FromCurrentSynchronizationContext()。

请在此处查看该问题的详细信息:SynchronizationContext.Current is null in Continuation on the main UI thread

该错误已在 .NET 4.5 中修复。