SynchronizationContext

SynchronizationContext

本文介绍了当前 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.

我猜这是因为测试是在工作线程上运行的.如何确保测试在主线程上运行?欢迎任何其他建议.

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

这篇关于当前 SynchronizationContext 不能用作 TaskScheduler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 18:23