Csharp/C#教程:为什么SynchronizationContext.Current为null?分享


为什么SynchronizationContext.Current为null?

错误: 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 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); } } } 

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

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

上述就是C#学习教程:为什么SynchronizationContext.Current为null?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/936608.html

(0)
上一篇 2021年11月7日
下一篇 2021年11月7日

精彩推荐