简体   繁体   中英

Best way to make multiple calls to API endpoint

I have designed the following method to call api within the loop. I was wondering if there is any other better way (performance) of calling APIs multiple times?

 private List<ClientInfo> populateDetails(List<ClientInfo> lstClientDetails)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = EndpointAddress;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            string Uri = "";
            ClientInfo clientInfo;

            foreach (var record in lstClientDetails)
            {
                Uri = string.Format("{0}", record.id);

                var postResponse = client.GetAsync(Uri).Result;

                if (postResponse.IsSuccessStatusCode)
                {
                    string result = postResponse.Content.ReadAsStringAsync().Result;

                    clientInfo = JsonConvert.DeserializeObject<ClientInfo>(result);

                    if (clientInfo != null)
                        record.email = clientInfo.email;
                }
            }

            return lstClientDetails;
        }
    }

Maybe you can change your code to use async/await pattern

private async Task populateDetails(List<ClientInfo> lstClientDetails)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = EndpointAddress;
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        string Uri = "";
        ClientInfo clientInfo;

        foreach (var record in lstClientDetails)
        {
            Uri = string.Format("{0}", record.id);

            var postResponse = await client.GetAsync(Uri);

            if (postResponse.IsSuccessStatusCode)
            {
                string result = await postResponse.Content.ReadAsStringAsync();

                clientInfo = JsonConvert.DeserializeObject<ClientInfo>(result);

                if (clientInfo != null)
                    record.email = clientInfo.email;
            }
        }
    }
}

And as you can see it doesn't make senso to return the same List which is passed as a paramters: the code will change the underlyne objects

Reference Microsoft Docs Parallel Library

sample code:


public class ParallelClient
{
    private async Task ParallelRequest(List<string> requests)
    {
        var responses = new ConcurrentBag<HttpResponseMessage>();
        using (var client = new HttpClient())
        {
            Parallel.ForEach(requests, new ParallelOptions { MaxDegreeOfParallelism = 10 }, async r =>
                {
                    var requestMessage = new HttpRequestMessage();
                    requestMessage.Method = HttpMethod.Post;
                    requestMessage.Content = new StringContent(r, Encoding.UTF8, "application/json");
                    var response = await client.SendAsync(requestMessage);
                    responses.Add(response);
                });
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM