ASP.NET Multithreading Web Requests

后端 未结 3 1437
南旧
南旧 2020-12-29 13:55

I\'m building a page in my ASP.NET solution that retrieves most of its data from a 3rd Party API Service.

The page itself will need to make approximately 5 individu

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 14:25

    Multithreading is not recommended on ASP.NET; because ASP.NET/IIS does its own multithreading, and any multithreading you do will interfere with those heuristics.

    What you really want is concurrency, more specifically asynchronous concurrency since your operations are I/O-bound.

    The best approach is to use HttpClient with the Task-based Asynchronous Pattern:

    public async Task GetOccupationAsync(string requestUrl)
    {
      // You can also reuse HttpClient instances instead of creating a new one each time
      using (var client = new HttpClient())
      {
        var response = client.GetStringAsync(requestUrl);
        return new JsonSerializer().Deserialize(new JsonTextReader(new StringReader(response)));
      }
    }
    

    This is asynchronous, and you can easily make it concurent by using Task.WhenAll:

    List urls = ...;
    OccupationSearch[] results = await Task.WhenAll(urls.Select(GetOccupationAsync));
    

提交回复
热议问题