How to limit the amount of concurrent async I/O operations?

前端 未结 14 2477
遇见更好的自我
遇见更好的自我 2020-11-22 01:27
// let\'s say there is a list of 1000+ URLs
string[] urls = { \"http://google.com\", \"http://yahoo.com\", ... };

// now let\'s send HTTP requests to each of these          


        
14条回答
  •  长情又很酷
    2020-11-22 02:20

    Use MaxDegreeOfParallelism, which is an option you can specify in Parallel.ForEach():

    var options = new ParallelOptions { MaxDegreeOfParallelism = 20 };
    
    Parallel.ForEach(urls, options,
        url =>
            {
                var client = new HttpClient();
                var html = client.GetStringAsync(url);
                // do stuff with html
            });
    

提交回复
热议问题