Task.ContinueWith not delaying

时间:2017-06-30 07:28:38

标签: c# asynchronous task task-parallel-library

为什么操作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();

2 个答案:

答案 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 asyncNeither does StartNew,就此而言。您不应该使用ContinueWithStartNew

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");