MSDN示例(re:https://msdn.microsoft.com/en-us/library/hh556530.aspx)演示了使用Async/Await
构造和LINQ
对象库运行多个异步I / O下载操作的技术,如下面的代码片段所示:< / p>
// Create a query.
IEnumerable<Task<int>> downloadTasksQuery =
from url in urlList select ProcessURLAsync(url);
// Use ToArray to execute the query and start the download tasks.
Task<int>[] downloadTasks = downloadTasksQuery.ToArray();
int[] lengths = await Task.WhenAll(downloadTasks);
async Task<int> ProcessURL(string url, HttpClient client)
{
byte[] byteArray = await client.GetByteArrayAsync(url);
DisplayResults(url, byteArray);
return byteArray.Length;
}
我正在寻找一个实现相同功能而不使用LINQ 的简单替代方案,即用一些核心Generics / Array C#方法替换这两行:
IEnumerable<Task<int>> downloadTasksQuery = from url in urlList select ProcessURLAsync(url);
Task<int>[] downloadTasks = downloadTasksQuery.ToArray();
答案 0 :(得分:1)
这很简单:
var taskList = new List<Task<int>>();
foreach(var url in urlList) {
taskList.Add(ProcessURLAsync(url));
}
Task<int>[] downloadTasks = taskList.ToArray();