Home > Net >  await does not resume on main thread
await does not resume on main thread

Time:12-26

Background

I faced this problem a couple of years ago and got enter image description here

As you can see, I have manually called SetSynchronizationContext before doing the await call. It also shows that SynchronizationContext.Current is set after it resumes after the await call, but somehow the code is still running on the worker thread. I also verified that the code was running on UI thread when it hit line 259 before drilling down into the await call.

I have already spent a lot of time and effort on this and can't make any sense of it. Can anyone help me figure out if I'm missing something obvious?

CodePudding user response:

You need to use an instance of the WindowsFormsSynchronizationContext class instead.

The WindowsFormsSynchronizationContext class provides a synchronization mechanism for Windows Forms.

The DispatcherSynchronizationContext class is for WPF applications which uses two threads. One thread is background thread for rendering and the other thread is for UI. So, UI elements in one thread are not accessible to other UI threads. Microsoft introduced the dispatcher which is responsible for multiple UI threads interaction.

  • Related