Parallel.Invoke does not wait for async methods to complete

前端 未结 2 695
遇见更好的自我
遇见更好的自我 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 03:55

    As you stated in your question, two of your methods query a database (one via sql, the other via azure) and the third triggers a POST request to a web service. All three of those methods are doing I/O bound work.

    What happeneds when you invoke Parallel.Invoke is you basically trigger three ThreadPool threads to block and wait for I/O based operations to complete, which is pretty much a waste of resources, and will scale pretty badly if you ever need to.

    Instead, you could use async apis which all three of them expose:

    1. SQL Server via Entity Framework 6 or ADO.NET
    2. Azure has async api's
    3. Web request via HttpClient.PostAsync

    Lets assume the following methods:

    LoadXAsync();
    LoadYAsync();
    LoadZAsync();
    

    You can call them like this:

    spinner.IsBusy = true;
    try
    {
        Task t1 = LoadXAsync();
        Task t2 = LoadYAsync();
        Task t3 = LoadZAsync();
    
        await Task.WhenAll(t1, t2, t3);
    }
    finally
    {
        spinner.IsBusy = false;
    }
    

    This will have the same desired outcome. It wont freeze your UI, and it would let you save valuable resources.

提交回复
热议问题