Task.Factory.StartNew with async lambda and Task.WaitAll

后端 未结 4 1532
小鲜肉
小鲜肉 2020-11-27 07:59

I\'m trying to use Task.WaitAll on a list of tasks. The thing is the tasks are an async lambda which breaks Tasks.WaitAll as it never waits.

4条回答
  •  天涯浪人
    2020-11-27 08:25

    This doesn't wait because of the async lambda. So how am I supposed to await I/O operations in my lambda?

    The reason Task.WaitAll doesn't wait for the completion of the IO work presented by your async lambda is because Task.Factory.StartNew actually returns a Task. Since your list is a List (and Task derives from Task), you wait on the outer task started by StartNew, while ignoring the inner one created by the async lambda. This is why they say Task.Factory.StartNew is dangerous with respect to async.

    How could you fix this? You could explicitly call Task.Unwrap() in order to get the inner task:

    List tasks = new List();
    tasks.Add(Task.Factory.StartNew(async () =>
    {
        using (dbContext = new DatabaseContext())
        {
            var records = await dbContext.Where(r => r.Id = 100).ToListAsync();
            //do long cpu process here...
        }
    }).Unwrap());
    

    Or like others said, you could call Task.Run instead:

    tasks.Add(Task.Run(async () => /* lambda */);
    

    Also, since you want to be doing things right, you'll want to use Task.WhenAll, why is asynchronously waitable, instead of Task.WaitAll which synchronously blocks:

    await Task.WhenAll(tasks);
    

提交回复
热议问题