How can SynchronizationContext.Current of the main thread become null in a Windows Forms application?

后端 未结 3 825
你的背包
你的背包 2020-11-30 03:14

I have a problem in my application: At some point, the SynchronizationContext.Current becomes null for the main thread. I\'m unable to reproduce the same problem in an isola

3条回答
  •  盖世英雄少女心
    2020-11-30 03:51

    Sly, I have run into the exact same behavior when a mixture of WPF, WCF, and TPL is used. The Main thread's current SynchronizationContext will become null in a few situations.

    var context = SynchronizationContext.Current;
    
    // if context is null, an exception of
    // The current SynchronizationContext may not be used as a TaskScheduler.
    // will be thrown
    TaskScheduler.FromCurrentSynchronizationContext();
    

    According to this post on the msdn forums, this is a confirmed bug in the TPL in 4.0. A coworker is running on 4.5 and does not see this behavior.

    We solved this by creating a TaskScheduler in a static singleton with the main thread using FromCurrentSynchronizationContext and then always reference that task scheduler when creating continuations. For example

    Task task = Task.Factory.StartNew(() =>
      {
        // something
      }
    ).ContinueWith(t =>
      {
        // ui stuff
      }, TheSingleton.Current.UiTaskScheduler);
    

    This avoids the issue in the TPL on .net 4.0.

    Update If you have .net 4.5 installed on your development machine, you will not see this issue even if you are targeting the 4.0 framework. Your users who only have 4.0 installed will still be affected.

提交回复
热议问题