簡體   English   中英

在C#中進行並行api調用並異步處理每個響應

[英]Making parallel api calls and handling each response asynchronously in c#

我有一種情況,我需要在c#(Xamarin iOS和Xamarin Android)中並行進行多個api調用(具有不同參數的相同api)。 而且我不想等待所有任務完成,而是每當收到響應時,我都應該處理它並相應地更新UI。

需要多次調用的方法

public  async Task<Response> GetProductsAsync(int categoryId, int pageNo = -1, int pageSize = -1)
        {
            try
            {
                string url = "";
                if (pageNo == -1 || pageSize == -1)
                    url = $"catalog/v1/categories/{categoryId}/products";
                else
                    url = $"catalog/v1/categories/{categoryId}/products?page-number={pageNo}&page-size={pageSize}";
                var response = await client.GetAsync(url);
                string responseString = await response.Content.ReadAsStringAsync();
                GetParsedData(response.IsSuccessStatusCode, responseString);
            }
            catch (Exception e)
            {
                apiResponse.status = "internalError";
                apiResponse.data = e.Message;
            }
            return apiResponse;
        }

通過調用函數,您可以編寫如下代碼

    public void CallingFunctionToGetProductsAsync() {
        Task.Run(async () =>
        {
            var response = await GetProductsAsync(1);
            ProcessResponse(response);
        });

        Task.Run(async () =>
        {
            var response = await GetProductsAsync(2);
            ProcessResponse(response);
        });
    }

這樣,您可以等待多個異步任務並在其中任何一個完成時更新UI。

async Task GetSomeProductsAsync( IEnumerable<int> categoryIds )
{
    List<Task<Response>> tasks = categoryIds
        .Select( catId => GetProductsAsync( catId ) )
        .ToList();

    while ( tasks.Any() )
    {
        var completed = await Task.WhenAny( tasks );
        tasks.Remove( completed );
        var response = completed.Result;
        // update the ui from this response
    }
}

附帶說明:

您應該在GetProducsAsync的等待代碼中添加ConfigureAwait(false) ,以避免與調用者線程不必要的同步(此處為UI)

public  async Task<Response> GetProductsAsync(int categoryId, int pageNo = -1, int pageSize = -1)
{
    try
    {
        string url = "";
        if (pageNo == -1 || pageSize == -1)
            url = $"catalog/v1/categories/{categoryId}/products";
        else
            url = $"catalog/v1/categories/{categoryId}/products?page-number={pageNo}&page-size={pageSize}";
        var response = await client.GetAsync(url).ConfigureAwait(false);
        string responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        GetParsedData(response.IsSuccessStatusCode, responseString);
    }
    catch (Exception e)
    {
        apiResponse.status = "internalError";
        apiResponse.data = e.Message;
    }
    return apiResponse;
}

您可以在Stephen Cleary的博客文章中了解有關它的更多信息: 不要阻止異步代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM