[英]Any scenario where Task.ContinueWith(…, TaskScheduler.FromCurrentSynchronizationContext()) would *not* run on the UI thread?
We are observing something strange, code like this: 我们正在观察一些奇怪的东西,代码如下:
var task = new Task(...); // run in the background, do something lengthy work
task.ContinueWith(..., TaskScheduler.FromCurrentSynchronizationContext());
task.Start();
The second task there calls an event, which in turn tries to update the GUI, and we get the dreaded cross-thread exception. 第二个任务调用一个事件,然后尝试更新GUI,我们得到了可怕的跨线程异常。
Checking Thread.CurrentThread.ManagedThreadId
from the method in the second task there indicates that it is in fact not running on the UI thread. 从第二个任务中的方法检查
Thread.CurrentThread.ManagedThreadId
表示它实际上没有在UI线程上运行。
The code that spawned the tasks is running on the UI thread. 这催生了任务的代码在UI线程上运行。
Is there any scenario where this will go wrong? 有什么情况会出错吗?
Presuming you are using .NET 4.0, there is a bug where the System.Threading.SynchronizationContext.Current
on the main thread can become null, and you would experience this problem. 假设您使用的是.NET 4.0,则主线程上的
System.Threading.SynchronizationContext.Current
可能会变为空,并且您会遇到此问题。 If you can reproduce the problem easily, the first thing to check is if SynchronizationContext.Current
is null when you call TaskScheduler.FromCurrentSynchronizationContext()
. 如果您可以轻松地重现问题,首先要检查的是当您调用
TaskScheduler.FromCurrentSynchronizationContext()
时, SynchronizationContext.Current
是否为null。
See the details of that problem here: SynchronizationContext.Current is null in Continuation on the main UI thread 请在此处查看该问题的详细信息: 在主UI线程的Continuation中,SynchronizationContext.Current为null
The bug is fixed in .NET 4.5. 该错误在.NET 4.5中得到修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.