Task.WaitAll not waiting for task to complete

前端 未结 4 711
攒了一身酷
攒了一身酷 2021-02-07 07:10

While trying to figure out the new (maybe not so new now, but new to me, anyway) Task asynchronous programming in C#, I ran into a problem that took me a bit to fig

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-07 08:11

    You should avoid using Task.Factory.StartNew with async-await. You should use Task.Run instead.

    An async method returns a Task, an async delegate does as well. Task.Factory.StartNew also returns a Task, where its result is the result of the delegate parameter. So when used together it returns a Task>>.

    All that this Task> does is execute the delegate until there's a task to return, which is when the first await is reached. If you only wait for that task to complete you aren't waiting for the whole method, just the part before the first await.

    You can fix that by using Task.Unwrap which creates a Task that represents that Task>>:

    Task wrapperTask = Task.Factory.StartNew(...);
    Task actualTask = wrapperTask.Unwrap();
    Task.WaitAll(actualTask);
    

提交回复
热议问题