【发布时间】:2013-12-05 23:19:35
【问题描述】:
在对使用任务延续和 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”方法中包含的代码永远不会到达如果我指定“TaskScheduler.FromCurrentSynchronizationContext()”。如果我删除此参数,则继续执行正确...
有什么想法或建议吗?
【问题讨论】:
-
为什么这种行为会让您感到惊讶?你希望
FromCurrentSynchronizationContext()在这里做什么? -
应该调用“ContinueWith”中的代码,但不是我上面解释的
标签: wpf unit-testing task-parallel-library dispatcher