Buy*_*uyo 5 .net c# asynchronous concurrent-processing
我在如何:通过使用异步和等待(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);
}
Run Code Online (Sandbox Code Playgroud)
我理解这段代码,但我的问题是:如何修改此代码以使其缩放为100或1000?
您可以在循环中调用异步调用。每次调用都可能返回一个任务,您必须等待所有任务完成
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);
Run Code Online (Sandbox Code Playgroud)
以上将调用多个请求并等待结果,但是 async\await 有助于在执行外部调用(http、db 等)时将线程释放给应用程序使用。但扩展取决于您的硬件和应用程序架构。
小智 8
由于帐户的限制,我无法发表评论,但是在回复@CreativeManix的回答时,
List<Task> tasks = new List<Task>();
Task.WaitAll(tasks)将不接受任务列表。它的替代之一接受任务数组。
Task.WaitAll(tasks.ToArray())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9051 次 |
| 最近记录: |