The current SynchronizationContext may not be used as a TaskScheduler

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

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

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.