The current SynchronizationContext may not be used as a TaskScheduler

C#MultithreadingNunitTask Parallel-LibraryResharper 6.0

C# Problem Overview


I am using Tasks to run long running server calls in my ViewModel and the results are marshalled back on Dispatcher using TaskScheduler.FromSyncronizationContext(). For example:

var context = TaskScheduler.FromCurrentSynchronizationContext();
this.Message = "Loading...";
Task task = Task.Factory.StartNew(() => { ... })
            .ContinueWith(x => this.Message = "Completed"
                          , context);

This works fine when I execute the application. But when I run my NUnit tests on Resharper I get the error message on the call to FromCurrentSynchronizationContext as:

> The current SynchronizationContext may not be used as a TaskScheduler.

I guess this is because the tests are run on worker threads. How can I ensure the tests are run on main thread ? Any other suggestions are welcome.

C# Solutions


Solution 1 - C#

You need to provide a SynchronizationContext. This is how I handle it:

[SetUp]
public void TestSetUp()
{
  SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
}

Solution 2 - C#

Ritch Melton's solution did not work for me. This is because my TestInitialize function is async, as are my tests, so with every await the current SynchronizationContext is lost. This is because as MSDN points out, the SynchronizationContext class is "dumb" and just queues all work to the thread pool.

What worked for me is actually just skipping over the FromCurrentSynchronizationContext call when there isn't a SynchronizationContext (that is, if the current context is null). If there's no UI thread, I don't need to synchronize with it in the first place.

TaskScheduler syncContextScheduler;
if (SynchronizationContext.Current != null)
{
    syncContextScheduler = TaskScheduler.FromCurrentSynchronizationContext();
}
else
{
    // If there is no SyncContext for this thread (e.g. we are in a unit test
    // or console scenario instead of running in an app), then just use the
    // default scheduler because there is no UI thread to sync with.
    syncContextScheduler = TaskScheduler.Current;
}

I found this solution more straightforward than the alternatives, which where:

  • Pass a TaskScheduler to the ViewModel (via dependency injection)
  • Create a test SynchronizationContext and a "fake" UI thread for the tests to run on - way more trouble for me that it's worth

I lose some of the threading nuance, but I am not explicitly testing that my OnPropertyChanged callbacks trigger on a specific thread so I am okay with that. The other answers using new SynchronizationContext() don't really do any better for that goal anyway.

Solution 3 - C#

I have combined multiple solution to have guarantee for working SynchronizationContext:

using System;
using System.Threading;
using System.Threading.Tasks;

public class CustomSynchronizationContext : SynchronizationContext
{
    public override void Post(SendOrPostCallback action, object state)
    {
        SendOrPostCallback actionWrap = (object state2) =>
        {
            SynchronizationContext.SetSynchronizationContext(new CustomSynchronizationContext());
            action.Invoke(state2);
        };
        var callback = new WaitCallback(actionWrap.Invoke);
        ThreadPool.QueueUserWorkItem(callback, state);
    }
    public override SynchronizationContext CreateCopy()
    {
        return new CustomSynchronizationContext();
    }
    public override void Send(SendOrPostCallback d, object state)
    {
        base.Send(d, state);
    }
    public override void OperationStarted()
    {
        base.OperationStarted();
    }
    public override void OperationCompleted()
    {
        base.OperationCompleted();
    }

    public static TaskScheduler GetSynchronizationContext() {
      TaskScheduler taskScheduler = null;

      try
      {
        taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
      } catch {}

      if (taskScheduler == null) {
        try
        {
          taskScheduler = TaskScheduler.Current;
        } catch {}
      }

      if (taskScheduler == null) {
        try
        {
          var context = new CustomSynchronizationContext();
          SynchronizationContext.SetSynchronizationContext(context);
          taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
        } catch {}
      }

      return taskScheduler;
    }
}

Usage:

var context = CustomSynchronizationContext.GetSynchronizationContext();

if (context != null) 
{
    Task.Factory
      .StartNew(() => { ... })
      .ContinueWith(x => { ... }, context);
}
else 
{
    Task.Factory
      .StartNew(() => { ... })
      .ContinueWith(x => { ... });
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionanivasView Question on Stackoverflow
Solution 1 - C#Ritch MeltonView Answer on Stackoverflow
Solution 2 - C#SapphView Answer on Stackoverflow
Solution 3 - C#ujeenatorView Answer on Stackoverflow