为什么ContinueWith()在上一个任务完成之前启动

时间:2019-04-17 15:33:45

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

我正在尝试创建一个任务,该任务将等待一段时间,然后继续进行一些任务后的工作。代码如下所示。如果我使用Thread.Sleep()作为等待时间,它将按预期工作。但是,如果我将Thread.Sleep()更改为等待Task.Delay(),则延续将在task1完成之前发生。怎么发生的?

class Program
{
    static void Main(string[] args)
    {

        Task t1 = Task.Factory.StartNew(async () => await DoSomeVeryImportantWork(1, 3))
                              .ContinueWith((prevTask)=> { Console.WriteLine("post task work!!!"); });

        Console.WriteLine("caller after starting tasks");
        Console.ReadKey();
    }

    static async Task DoSomeVeryImportantWork(int id, int sleeptimeInSeconds)
    {
        Stopwatch stopWatch = new Stopwatch();

        Console.WriteLine($"t{id} is beginning");

        stopWatch.Start();
        //Thread.Sleep(TimeSpan.FromSeconds(sleeptimeInSeconds));
        await Task.Delay(TimeSpan.FromSeconds(sleeptimeInSeconds));
        stopWatch.Stop();

        TimeSpan ts = stopWatch.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
           ts.Hours, ts.Minutes, ts.Seconds,
           ts.Milliseconds / 10);
        Console.WriteLine($"t{id} sleeping time -  " + elapsedTime);
        Console.WriteLine($"t{id} has completed ");
    }

}

预期输出:(如果我使用thread.sleep()而不是task.delay(),这也是输出

caller after starting tasks
t1 is beginning
t1 sleeping time -  00:00:03.00
t1 has completed
post task work!!!

实际输出:

caller after starting tasks
t1 is beginning
post task work!!!
t1 sleeping time -  00:00:03.01
t1 has completed

1 个答案:

答案 0 :(得分:1)

@Steve权利。 await返回一个新的Task-等于Task.Factory.StartNew(() => DoSomeVeryImportantWork(1, 3)) ...您有两个选择:

1)使用Task.Run()正确处理异步任务:

Task t1 = Task.Run(() => DoSomeVeryImportantWork(1, 3));
// Or
Task t1 = Task.Run(async () => await DoSomeVeryImportantWork(1, 3));

2)不要呼叫Task.Factory.StartNew()。只需调用async方法,任务就会自动启动:

Task t1 = DoSomeVeryImportantWork(1, 3);