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
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.