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

时间:2010-11-13 21:25:57

标签: c# asynchronous task async-await

我认为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的本质究竟是什么?

2 个答案:

答案 0 :(得分:3)

对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!");

    }

答案 1 :(得分:2)

WhenAll()创建一个在所有子任务完成时完成的任务。因此,该方法本身不会完成,但任务将会完成。

这是一种创建新任务的方法,该任务将单独的任务聚合到一个新的更大的任务中。