简体   繁体   English

如何使用async和await创建大量并发Web请求?

[英]How to make a lot of concurrent web requests using async and await?

I read the how to by Microsoft at How to: Make Multiple Web Requests in Parallel by Using async and await (C#) and found: 我在如何:通过使用async和等待(C#)并行创建多个Web请求时阅读了Microsoft 如何找到:

private async Task CreateMultipleTasksAsync()  
{  
    // Declare an HttpClient object, and increase the buffer size. The  
    // default buffer size is 65,536.  
    HttpClient client =  
        new HttpClient() { MaxResponseContentBufferSize = 1000000 };  

    // Create and start the tasks. As each task finishes, DisplayResults   
    // displays its length.  
    Task<int> download1 =   
        ProcessURLAsync("http://msdn.microsoft.com", client);  
    Task<int> download2 =   
        ProcessURLAsync("http://msdn.microsoft.com/library/hh156528(VS.110).aspx", client);  
    Task<int> download3 =   
        ProcessURLAsync("http://msdn.microsoft.com/library/67w7t67f.aspx", client);  

    // Await each task.  
    int length1 = await download1;  
    int length2 = await download2;  
    int length3 = await download3;  

    int total = length1 + length2 + length3;  

    // Display the total count for the downloaded websites.  
    resultsTextBox.Text +=  
        string.Format("\r\n\r\nTotal bytes returned:  {0}\r\n", total);  
}  

I understand this code, but my question is: How do I modify this to scale it to like, let's say a hundred or a thousand? 我理解这段代码,但我的问题是:如何修改它以将其缩放为喜欢,让我们说一百或一千?

I can't comment due to the restriction on my account, but in reply to @CreativeManix's answer, 由于我的帐户受到限制,我无法发表评论,但在回复@ CreativeManix的回答时,

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

Task.WaitAll(tasks) will not accept a List of Tasks. Task.WaitAll(tasks)不接受任务列表。 One of its override accepts an Array of Tasks. 其中一个覆盖接受一个任务数组。

Task.WaitAll(tasks.ToArray())

You can invoke async calls in loop. 您可以在循环中调用异步调用。 Each call could return a Task, and you have to wait for all Tasks to complete 每次调用都可以返回一个Task,您必须等待所有任务完成

var requestInfoCollection = new RequestInfo[]
{
     new RequestInfo("http://url1","GET"),
     new RequestInfo("http://url2","GET"),
     new RequestInfo("http://url2","POST")
};
List<Task> tasks = new List<Task>();
foreach(var requestInfo in requestInfoCollection)
{
   tasks.Add(ProcessURLAsync(requestInfo))
}
Task.WaitAll(tasks);

The above will invoke multiple requests and waits for results, however async\\await is helpful to release thread to application to use while performing external invocations (http, db etc...). 以上将调用多个请求并等待结果,但是async \\ await有助于在执行外部调用(http,db等...)时将线程释放给应用程序。 But scaling is depends on your hardware, and your application architecture. 但扩展取决于您的硬件和应用程序架构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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