Parallel.Invoke does not wait for async methods to complete

前端 未结 2 697
遇见更好的自我
遇见更好的自我 2020-12-09 03:28

I have an application that pulls a fair amount of data from different sources. A local database, a networked database, and a web query. Any of these can take a few seconds t

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 04:01

    It sounds like you really want something like:

    spinner.IsBusy = true;
    try
    {
        Task t1 = Task.Run(() => dataX = loadX());
        Task t2 = Task.Run(() => dataY = loadY());
        Task t3 = Task.Run(() => dataZ = loadZ());
    
        await Task.WhenAll(t1, t2, t3);
    }
    finally
    {
        spinner.IsBusy = false;
    }
    

    That way you're asynchronously waiting for all the tasks to complete (Task.WhenAll returns a task which completes when all the other tasks complete), without blocking the UI thread... whereas Parallel.Invoke (and Parallel.ForEach etc) are blocking calls, and shouldn't be used in the UI thread.

    (The reason that Parallel.Invoke wasn't blocking with your async lambdas is that it was just waiting until each Action returned... which was basically when it hit the start of the await. Normally you'd want to assign an async lambda to Func or similar, in the same way that you don't want to write async void methods usually.)

提交回复
热议问题