Why is SynchronizationContext.Current null?

后端 未结 1 550
[愿得一人]
[愿得一人] 2021-01-04 20:12

Error: Object reference not set to an instance of an object.

The algorithm below works. I tried it, then I removed the Winform project to a

相关标签:
1条回答
  • 2021-01-04 21:14

    Your code critically depends on exactly when and where the constructor of your class runs. SynchronizationContext.Current will be null when:

    • your class object is created too soon, before your code creates an instance of the Form class or calls Application.Run() in Main(). That's when the Current member is set to an instance of WindowsFormsSynchronizationContext, the class that knows how to marshal calls with the message loop. Fix this by moving your object instancing code to the main form constructor.

    • your class object is created on any thread other than the main UI thread. Only the UI thread in a Winforms application can marshal calls. Diagnose this by adding a constructor to your class with this statement:

        Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
      

    Also add this line to the Main() method in Program.cs. It won't work if the displayed value in the Output window is different. Fix this by moving your object instancing code to, again, the main form constructor so you can be sure it runs on the UI thread.

    0 讨论(0)
提交回复
热议问题