21

I just wrote this code:

System.Threading.SynchronizationContext.Current.Post(
    state => DoUpdateInUIThread((Abc)state), 
    abc);

but System.Threading.SynchronizationContext.Current is null

madth3
  • 7,151
  • 12
  • 47
  • 72
Ian Ringrose
  • 50,487
  • 53
  • 210
  • 311

2 Answers2

20

To get it to work.

In your class

private SynchronizationContext synchronizationContext;

In the UI thread (main thread)

synchronizationContext = System.Threading.SynchronizationContext.Current;

In the worker thread

synchronizationContext.Post(    
   state => DoUpdateInUIThread((Abc)state),     
   abc);
Ian Ringrose
  • 50,487
  • 53
  • 210
  • 311
  • How is the syncronizationContext instantiated in, or passed to, the worker thread? – Tim Jun 02 '13 at 01:46
  • Let's say you're using a `BackgroundWorker` in your form. If you save off `SynchronizationContext.Current` in your constructor or load event as a class level variable, it'll be accessible in the `RunWorkerCompleted` handler. Alternatively, if you're doing the work in another class, like a presenter, you could create the presenter on the UI thread and save off the context in the constructor. – Jeff B Jun 20 '13 at 19:20
16

See this explanation.

SynchronizationContext.Current is only set in the main thread (which is the only thread where you don't actually need it)

The blog post proposes a workaround.

Marcel Gosselin
  • 4,550
  • 2
  • 27
  • 51