简体   繁体   中英

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.

Checking Thread.CurrentThread.ManagedThreadId from the method in the second task there indicates that it is in fact not running on the UI thread.

The code that spawned the tasks is running on the UI thread.

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. If you can reproduce the problem easily, the first thing to check is if SynchronizationContext.Current is null when you call TaskScheduler.FromCurrentSynchronizationContext() .

See the details of that problem here: SynchronizationContext.Current is null in Continuation on the main UI thread

The bug is fixed in .NET 4.5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM