gpt4 book ai didi

c# - 异步 CTP 中的 `TaskEx.WhenAll` 是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 20:38:17 25 4
gpt4 key购买 nike

我认为 TaskEx.WhenAll 会在方法中传递的所有任务完成后返回。所以在 TaskEx.WhenAll 上等待将返回 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 的本质是什么?

最佳答案

对 TaskEx.WhenAll 的调用发生在 for 循环内。你必须把它放在外面。

public static 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
{
Console.WriteLine("Calling server...");
Task<string> task = client.DownloadStringTaskAsync(new Uri("http://www.msn.com"));
lstTasks.Add(task);

}
catch (Exception ex)
{
Console.WriteLine("Error occurred!");
}
}

}

string[] rss = await TaskEx.WhenAll<string>(lstTasks);
foreach (string s in rss)
builder.Append(s);

Console.WriteLine("Downloaded!");

}

关于c# - 异步 CTP 中的 `TaskEx.WhenAll` 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4174806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com