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

后端 未结 3 827
你的背包
你的背包 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:44

    I've created a class for this. It looks like this:

    public class UIContext
    {
        private static TaskScheduler m_Current;
    
        public static TaskScheduler Current
        {
            get { return m_Current; }
            private set { m_Current = value; }
        }
    
        public static void Initialize()
        {
            if (Current != null)
                return;
    
            if (SynchronizationContext.Current == null)
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
    
            Current = TaskScheduler.FromCurrentSynchronizationContext();
        }
    }
    

    On startup of my App I call UIContext.Initialize()

    And when I need it in a task I just put UIContext.Current as TaskScheduler.

    Task.Factory.StartNew(() =>
    {
        //Your code here
    }, CancellationToken.None, TaskCreationOptions.None, UIContext.Current);
    

提交回复
热议问题