Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is SynchronizationContext.Current null in my Winforms application?

I just wrote this code:

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

but System.Threading.SynchronizationContext.Current is null

like image 529
Ian Ringrose Avatar asked Nov 10 '09 17:11

Ian Ringrose


2 Answers

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);
like image 148
Ian Ringrose Avatar answered Nov 07 '22 22:11

Ian Ringrose


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.

like image 30
Marcel Gosselin Avatar answered Nov 07 '22 23:11

Marcel Gosselin