1
\$\begingroup\$

I have the following code that makes a call to an external API, processes the response and returns a string. The problem is it is taking a very long time to process. I can't do anything to the API, but I was just wondering if there is a better way of doing the rest of the code.

foreach(var item in products)
{
    item.site = await _testRepo.GetSiteLink(item.Id, item.baseLink);
}

And the GetSiteLink method in a different class.

public async Task<string> GetSiteLink(int itemId, string baseLink)
{
    var encodedUrl = HttpUtility.UrlEncode(baseLink);
    var response = await _client.GetAsync($"apilink/{itemId}/?ulp={encodedUrl}");
    if (response.IsSuccessStatusCode)
    {
        var responseContent = await response.Content.ReadAsStringAsync();
        var parsedResponse = JsonConvert.DeserializeObject<string[]>(responseContent);
        return HttpUtility.UrlDecode(parsedResponse[0]);
    }
    return "";
}
\$\endgroup\$
2
  • \$\begingroup\$ IDisposable: using var response = await .... It would allow to reuse the opened server connections faster. \$\endgroup\$
    – aepot
    Commented May 7, 2021 at 21:35
  • \$\begingroup\$ Also answers in this question might be useful. \$\endgroup\$
    – aepot
    Commented May 7, 2021 at 21:40

1 Answer 1

2
\$\begingroup\$

one way of solving this would be using Task.WhenAll the idea is to add all tasks into a list of tasks then we call Task.WhenAll and await the final results.

Here is an example of it :

private async Task<ProductItem> SetSiteLink(ProductItem item)
{   
    item.site = await _testRepo.GetSiteLink(item.Id, item.baseLink); 
    
    return Task.FromResult(item);  
}

then call it like this :

var tasks = new List<Task<ProductItem>>();

foreach (var item in products)
{
    tasks.Add(SetSiteLink(item));
}

var results = await Task.WhenAll(tasks);
\$\endgroup\$
1
  • \$\begingroup\$ Depending on the size of the products and overloadness of the downstream system this approach could make the situation even worse. Instead of issuing a single request against a service which is already struggling you issue N requests. The chance of failure (or timeout) might increase with this approach. I would suggest this approach only with throttling. \$\endgroup\$ Commented May 10, 2021 at 7:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.