【问题标题】:Why is SynchronizationContext.Current null in my Winforms application?为什么我的 Winforms 应用程序中 SynchronizationContext.Current 为空?
【发布时间】:2009-11-10 17:06:40
【问题描述】:

我刚刚写了这段代码:

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

但 System.Threading.SynchronizationContext.Current 为空

【问题讨论】:

    标签: c# winforms multithreading synchronizationcontext


    【解决方案1】:

    让它工作。

    在你的课堂上

    private SynchronizationContext synchronizationContext;
    

    UI线程(主线程)

    synchronizationContext = System.Threading.SynchronizationContext.Current;
    

    在工作线程中

    synchronizationContext.Post(    
       state => DoUpdateInUIThread((Abc)state),     
       abc);
    

    【讨论】:

    • syncronizationContext 如何在工作线程中实例化或传递给工作线程?
    • 假设您在表单中使用了BackgroundWorker。如果您在构造函数中保存 SynchronizationContext.Current 或将事件加载为类级别变量,则可以在 RunWorkerCompleted 处理程序中访问它。或者,如果您在另一个类中进行工作,例如演示者,您可以在 UI 线程上创建演示者并在构造函数中保存上下文。
    【解决方案2】:

    this explanation

    SynchronizationContext.Current 仅在主线程中设置(这是您实际上不需要它的唯一线程)

    博客文章提出了一种解决方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      相关资源
      最近更新 更多