我认为 TaskEx.WhenAll 会在方法中传递的所有任务完成时返回。因此,TaskEx.WhenAll 上的 await 将返回 Return 语句的数组,这样当每个对象完成时,将返回该数组。
但事实并非如此。当我做 :
public async Task AsynchronousCallServerMordernParallelAsync()
{
List<Task<string>> lstTasks = new List<Task<string>>();
StringBuilder builder = new StringBuilder();
for (int i = 2; i <= 10; i++)
{
using (WebClient client = new WebClient())
{
try
{
this.tbStatus.Text = string.Format("Calling Server [{0}]..... ", i);
string currentCall = string.Format(Feed, i);
Task<string> task = client.DownloadStringTaskAsync(new Uri(currentCall));
lstTasks.Add(task);
}
catch (Exception ex)
{
this.tbStatus.Text = string.Format("Error Occurred -- {0} for call :{1}, Trying next", ex.Message, i);
}
}
string[] rss = await TaskEx.WhenAll<string>(lstTasks);
foreach(string s in rss)
builder.Append(s);
MessageBox.Show(string.Format("Downloaded Successfully!!! Total Size : {0} chars.", builder.Length));
}
}
我看到我的 MessageBox 出现了不止一次,并且还等待步骤中包含 1 个元素的数组,然后是 2 个元素的数组,依此类推。
谁能告诉我 TakEx.WhenAll 的本质是什么?