为什么操作1和2同时执行?而不是相隔30秒?
在ASP.NET上的IIS下运行
Task t = Task.Factory.StartNew(() =>
{
Console.WriteLine("Operation 1");
}
).ContinueWith(async task =>
{
log("sleeping during turn on");
await Task.Delay(25000);
log("finished awaiting");
Thread.Sleep(5000);
log("finished sleeping");
}
).ContinueWith(
task =>
{
Console.WriteLine("Operation 2");
}
);
t.Wait();
答案 0 :(得分:2)
首先ContinueWith
返回Task<Task>
,您需要.Unwrap
:
Task t = Task.Factory.StartNew(() => {
Console.WriteLine("Operation 1");
})
.ContinueWith(async task => {
log("sleeping during turn on");
await Task.Delay(25000);
log("finished awaiting");
Thread.Sleep(5000);
log("finished sleeping");
})
.Unwrap()
.ContinueWith(task => {
Console.WriteLine("Operation 2");
});
t.Wait();
为了更深入地理解,您可以检查ContinueWith
的所有实现:
它在第一个ContinueWith
中使用,在第二个中使用。
同时检查async task => { ...
,您需要了解它会返回Task
。
最后的澄清(如果它不是关于理解ContinueWith
的问题),最好使用await
:
Task t = Task.Factory.StartNew(async () => {
Console.WriteLine("Operation 1");
log("sleeping during turn on");
await Task.Delay(25000);
log("finished awaiting");
Thread.Sleep(5000);
log("finished sleeping");
Console.WriteLine("Operation 2");
});
t.Wait();
答案 1 :(得分:-1)
为什么操作1和2同时执行?而不是相隔30秒?
简短的回答是ContinueWith
does not understand async
。 Neither does StartNew
,就此而言。您不应该使用ContinueWith
或StartNew
。
Instead of StartNew
, use Task.Run
,而不是ContinueWith
,请使用await
:
Task t = Task.Run(async () =>
{
Console.WriteLine("Operation 1");
log("sleeping during turn on");
await Task.Delay(25000);
log("finished awaiting");
Thread.Sleep(5000);
log("finished sleeping");
Console.WriteLine("Operation 2");
});
t.Wait();
在ASP.NET上的IIS下运行
由于您使用的是ASP.NET,you shouldn't be using Task.Run
, either:
Console.WriteLine("Operation 1");
log("sleeping during turn on");
await Task.Delay(25000);
log("finished awaiting");
Thread.Sleep(5000);
log("finished sleeping");
Console.WriteLine("Operation 2");