Why is SynchronizationContext.Current null in my Winforms application?

左心房为你撑大大i 提交于 2019-12-18 04:31:26

问题


I just wrote this code:

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

but System.Threading.SynchronizationContext.Current is null


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/1709552/why-is-synchronizationcontext-current-null-in-my-winforms-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!