Why is SynchronizationContext.Current null in my Winforms application?
Asked Answered
S

2

22

I just wrote this code:

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

but System.Threading.SynchronizationContext.Current is null

Shipworm answered 10/11, 2009 at 17:6 Comment(0)
Y
17

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.

Yatzeck answered 10/11, 2009 at 17:10 Comment(0)
S
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);
Shipworm answered 10/11, 2009 at 17:11 Comment(2)
How is the syncronizationContext instantiated in, or passed to, the worker thread?Raynaraynah
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.Zolazoldi
Y
17

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.

Yatzeck answered 10/11, 2009 at 17:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.