9

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • 1
    Why create the task directly instead of running Task.StartNew? – Panagiotis Kanavos Mar 20 '13 at 13:22
  • @PanagiotisKanavos, there can be legitimate reasons for doing this (see http://blogs.msdn.com/b/pfxteam/archive/2010/06/13/10024153.aspx), but this is not germane to the question. – Matt Smith Mar 20 '13 at 13:36
  • Well, I can't repro this, nor have I encountered this situation, or the context becoming null, unless the call to create the tasks wasn't really made in the UI thread in the first place – Panagiotis Kanavos Mar 20 '13 at 13:38
  • The 1st thing I'd do is to check what `TaskScheduler.FromCurrentSynchronizationContext` returns in the debugger. What do you find when you do this? – usr Mar 20 '13 at 13:47
  • @Lasse, did you find the reason or a solution to this problem? – shaibee Nov 03 '15 at 10:27
  • Yes, have forgotten to mark the answer as accepted. The problem was .net 4.0 and null synchronization context, so a new context is being created at some point, unrelated to the gui thread. – Lasse V. Karlsen Nov 03 '15 at 11:16

1 Answers1

4

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.

Community
  • 1
  • 1
Matt Smith
  • 17,026
  • 7
  • 53
  • 103