c# - SynchronizationContext.Current 在主线程上为空

标签 c# wpf multithreading winforms synchronizationcontext

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

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。以下是此类证据的一些屏幕截图:

enter image description here enter image description here

它也与 this 等帖子无关因为我使用的是较新的 .NET 版本,而且似乎提到的问题已经修补。还有其他好的想法吗?

最佳答案

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

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

关于c# - SynchronizationContext.Current 在主线程上为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45054201/

相关文章:

c# - 为什么并发修改数组这么慢?

c# - 从 MethodInfo 生成 DynamicMethod

c# - 如何在 WPF 上有效替换高频图像

c# - 为什么在 Storyboard设置动画时属性上的设置函数不更新

c# - 为什么将TextBox的Value重置为先前的值而不显示错误?

java swing 多线程绘制

java - 安卓蓝牙 : onCharacteristicRead() appears to be blocked by thread

c# - C# 中的错误 - "FooBar".StartsWith(string.Empty) 为 true

c# - 找不到合适的方法来覆盖 OnModelCreating()

c# - 一台服务器许多客户端 : Threads or classes