相关疑难解决方法(0)

为什么Task.ContinueWith无法在此单元测试中执行?

我遇到了单元测试失败的问题,因为TPL任务从未执行过它ContinueWith(x, TaskScheduler.FromCurrentSynchronizationContext()).

问题原因是因为在启动任务之前意外创建了Winforms UI控件.

这是一个再现它的例子.您将看到,如果您按原样运行测试,它将通过.如果在未取消注释表单行的情况下运行测试,则会失败.

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        // Create new sync context for unit test
        SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

        var waitHandle = new ManualResetEvent(false);

        var doer = new DoSomethinger();

        //Uncommenting this line causes the ContinueWith part of the Task
        //below never to execute.
        //var f = new Form();

        doer.DoSomethingAsync(() => waitHandle.Set());

        Assert.IsTrue(waitHandle.WaitOne(10000), "Wait timeout exceeded.");
    }
}


public class DoSomethinger
{
    public void DoSomethingAsync(Action onCompleted)
    {
        var task = Task.Factory.StartNew(() => Thread.Sleep(1000)); …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing winforms task-parallel-library

10
推荐指数
1
解决办法
1031
查看次数