Ian Ringrose
Ian Ringrose

Reputation: 51897

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

Upvotes: 22

Views: 18894

Answers (2)

Marcel Gosselin
Marcel Gosselin

Reputation: 4716

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.

Upvotes: 17

Ian Ringrose
Ian Ringrose

Reputation: 51897

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);

Upvotes: 20

Related Questions