Task.ContinueWith和DispatcherSynchronizationContext [英] Task.ContinueWith and DispatcherSynchronizationContext

查看:187
本文介绍了Task.ContinueWith和DispatcherSynchronizationContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单元测试使用任务继续和DispatcherSynchrinizationContext的代码时,我遇到一个我不理解的问题。

I'm facing an issue that I do not understand when unit testing a code that uses task continuation and DispatcherSynchrinizationContext.

我的单元测试代码:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());

        var class1 = new Class1();
        var result = class1.MyAsyncMethod().Result;

        Assert.IsTrue(result == "OK");
    }
}

正在测试的代码:

class Class1
{
    public Task<string> MyAsyncMethod()
    {
        var tcs = new TaskCompletionSource<string>();

        MyInnerAsyncMethod()
            .ContinueWith(t =>
            {
                // Never reached if TaskScheduler.FromCurrentSynchronizationContext() is set
                tcs.SetResult("OK");

            }, TaskScheduler.FromCurrentSynchronizationContext());

        return tcs.Task;
    }


    private Task<string> MyInnerAsyncMethod()
    {
        var tcs = new TaskCompletionSource<string>();
        tcs.SetResult("OK");
        return tcs.Task;
    }
}

问题是 ContinueWith IF 永远不会达到我指定 TaskScheduler.FromCurrentSynchronizationContext()的方法。如果删除此参数,则继续操作可以正确执行...

The problem is that the code contained within the "ContinueWith" method is never reached IF I specify "TaskScheduler.FromCurrentSynchronizationContext()". If I remove this parameter, the continuation executes correctly ...

有任何想法或建议吗?

推荐答案

我认为这是因为尽管您创建了一个新的DispatcherSynchronisationContext,但是没有实际的线程运行一个分派循环来执行您的任务。

I think this is because although you have created a new DispatcherSynchronisationContext, there is no actual thread running a dispatch loop for your task to execute on.

尝试将其放在测试的开始:

Try putting this at the beginning of your test:

// Create a thread
Thread newWindowThread = new Thread(new ThreadStart( () =>
{
    // Create our context, and install it:
    SynchronizationContext.SetSynchronizationContext(
        new DispatcherSynchronizationContext(
            Dispatcher.CurrentDispatcher));

    // Start the Dispatcher Processing
    System.Windows.Threading.Dispatcher.Run();
}));

礼貌:
http://reedcopsey.com/2011/11/28/launching-a- wpf-window-in-a-separate-thread-part-1 /

这篇关于Task.ContinueWith和DispatcherSynchronizationContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆