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
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);