4

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?

Aldracor
  • 2,133
  • 1
  • 19
  • 27
VidasV
  • 4,335
  • 1
  • 28
  • 50
  • 1
    Exactly where is SynchronizationContext.Current null? Please provide a repo of your issue when asking a question: https://stackoverflow.com/help/mcve – mm8 Jul 12 '17 at 09:49
  • https://stackoverflow.com/questions/1709552/why-is-synchronizationcontext-current-null-in-my-winforms-application – Vladimir Arustamian Jul 12 '17 at 10:01
  • @mm8 - Updated. VladimirArustamian - this is not the case for me. I have mentioned that in the last paragraph in my original post. – VidasV Jul 12 '17 at 11:37

1 Answers1

3

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.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • That is totally true. In my case there is no formal application as it is a multi-window workspace so I need to initialize my first form to force context creation. – VidasV Jul 12 '17 at 13:08