Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SynchronizationContext.Current is null on Main thread

SynchronizationContext.Current is null on Main thread and I have had a hard time figuring this one out.

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

I am running on .NET 4.6.1. It is a mixed Winforms and WPF app. The entry point is WinForms. Here are some screenshots of such evidence:

enter image description here enter image description here

It is also not related to posts like this as I am using newer .NET version and seems mentioned issue was patched already. Any other good ideas?

like image 701
VidasV Avatar asked Oct 18 '25 15:10

VidasV


1 Answers

Of course there is no SynchronizationContext available when the entry point (Main) of your application is hit. You need to wait for the framework to initialize it.

In a Windows Forms application this happens when the first form is created. So only after the Application.Run method has been called, the SynchronizationContext.Current property will actually return a synchronization context.

like image 91
mm8 Avatar answered Oct 21 '25 05:10

mm8