为什么SynchronizationContext.Current为null?

Dmi*_*iyd 8 .net c# multithreading winforms

错误: Object reference not set to an instance of an object.

下面的算法有效.我尝试了,然后我将Winform项目删除到另一个目录,SynchronizationContext.Currentnull.为什么?

SynchronizationContext uiCtx = SynchronizationContext.Current;  

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    int[] makeSelfMoves = new int[4];

    lock (replay)
    {
        // count should be more than 2
        foreach (KeyValuePair<int, int[]> item in replay)
        {              
            makeSelfMoves = replay[item.Key];
            codeFile.ExecuteAll(makeSelfMoves[0],
              makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);

            // i get the error here. uictx is null
            uiCtx.Post(o =>
            {
                PrintPieces(codeFile.PieceState());
            }, null);                               

            System.Threading.Thread.Sleep(1000);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 17

您的代码严格依赖于类的构造函数的运行时间和位置.在以下情况下,SynchronizationContext.Current将为null:

  • 在您的代码创建Form类的实例或在Main()中调用Application.Run()之前,您的类对象会很快创建.当Current成员设置为WindowsFormsSynchronizationContext的实例时,该类知道如何使用消息循环封送调用.通过将对象实例化代码移动到主窗体构造函数来解决此问题.

  • 您的类对象是在主UI线程以外的任何线程上创建的.只有Winforms应用程序中的UI线程才能封送调用.通过使用以下语句向您的类添加构造函数来诊断:

            Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
    
    Run Code Online (Sandbox Code Playgroud)

还要将此行添加到Program.cs中的Main()方法中.如果"输出"窗口中的显示值不同,则无效.通过将对象实例化代码再次移动到主窗体构造函数来解决此问题,以便确保它在UI线程上运行.