【问题标题】:SynchronizationContext.Current is null on Main threadSynchronizationContext.Current 在主线程上为空
【发布时间】:2017-07-12 09:47:24
【问题描述】:

SynchronizationContext.Current 在主线程上为空,我很难弄清楚这一点。

static class Program
{
        /// <summary>
        /// The main entry point for the application.
        /// </summary>

        [STAThread]
        static void Main(string[] args)
        {
            var ctx = System.Threading.SynchronizationContext.Current;
            // ctx is null here
        }
}

我在 .NET 4.6.1 上运行。它是一个混合的 Winforms 和 WPF 应用程序。入口点是 WinForms。以下是此类证据的一些截图:

它也与 this 之类的帖子无关,因为我使用的是较新的 .NET 版本,并且似乎提到的问题已经修复。还有什么好主意吗?

【问题讨论】:

标签: c# wpf multithreading winforms synchronizationcontext


【解决方案1】:

当您的应用程序的入口点 (Main) 被命中时,当然没有可用的 SynchronizationContext。您需要等待框架对其进行初始化。

在 Windows 窗体应用程序中,这发生在创建第一个窗体时。所以只有在调用了Application.Run 方法之后,SynchronizationContext.Current 属性才会真正返回一个同步上下文。

【讨论】:

  • 完全正确。就我而言,没有正式的应用程序,因为它是一个多窗口工作区,所以我需要初始化我的第一个表单以强制创建上下文。
猜你喜欢
  • 2012-07-22
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多