2
我有一个长时间运行的任务方法,使用睡眠异步CTP V3,MS测试和Thread.sleep代码
public Task LongRunning() {
return Task.Factory.StartNew(
() => {
Trace.TraceInformation("Start Sleep");
Thread.Sleep(10000);
Trace.TraceInformation("End Sleep");
});
}
这是我的测试调用,它工作正常
[TestMethod]
public void SimpleContinueWith() {
Trace.TraceInformation("Start");
LongRunning()
.ContinueWith(
t => Trace.TraceInformation("End")
).Wait();
}
> QTAgent32.exe Information: 0 : Start
> QTAgent32.exe Information: 0 : Start Sleep
> QTAgent32.exe Information: 0 : End Sleep
> QTAgent32.exe Information: 0 : End
但使用异步/等待测试直接通过
[TestMethod]
public async void SimpleAwait() {
Trace.TraceInformation("Start");
await LongRunning();
Trace.TraceInformation("End");
}
> QTAgent32.exe Information: 0 : Start
> QTAgent32.exe Information: 0 : Start Sleep
为什么呢?
超,谢谢,安装NuGet包http://nuget.org/List/Packages/Nito.AsyncEx –
顺便说一句,我在写测试的原因是因为我有一个调用Parallel.ForEach和递归的Async方法 - 它不能与async/await一起工作,就像上面的测试行为一样,即被调用并永不回来。 AsyncContext解决了这个问题 - 再次感谢 –