当前 SynchronizationContext 不能用作 TaskScheduler

当前 SynchronizationContext 不能用作 TaskScheduler

问题描述:

我正在使用 任务 长时间运行服务器在我的 ViewModel 中调用,结果使用 TaskScheduler.FromSyncronizationContext() 编组回 Dispatcher.例如:

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

这在我执行应用程序时工作正常.但是当我在 Resharper 上运行我的 NUnit 测试时,我在调用 FromCurrentSynchronizationContext 时收到错误消息:

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:

当前的 SynchronizationContext 不能用作 TaskScheduler.

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.

您需要提供一个 SynchronizationContext.我是这样处理的:

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

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