ASP.NET Multithreading Web Requests

后端 未结 3 1423
南旧
南旧 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:38

    I would argue that Multithreading (within reason) would provide benefits as the way your code is written know the calls to GetResponse().GetResponseStream() are blocking.

    One of the easiest ways to improve performance is to use a Parallel.ForEach:

            var urls = new List();
    
            var results = new ConcurrentBag();
    
            Parallel.ForEach(urls, url =>
            {
                WebRequest request = WebRequest.Create(requestUrl);
    
                string response = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
    
                var result = JsonSerializer().Deserialize(new JsonTextReader(new StringReader(response)));
    
                results.Add(result);
            });
    

    If you are using .NET 4.5 the new approach is to use async/await. Msdn has a pretty extensive article on this very topic here: http://msdn.microsoft.com/en-us/library/hh300224.aspx and http://msdn.microsoft.com/en-us/library/hh696703.aspx

    Scott Hanselman also has a good looking Blog Post on this topic: http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx

提交回复
热议问题