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.
You need to provide a SynchronizationContext. This is how I handle it:
[SetUp]
public void TestSetUp()
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
}