开发者

What is `TaskEx.WhenAll` in the Async CTP?

I thought TaskE开发者_Python百科x.WhenAll would return when all the tasks gets finished which is passed within the method. So await on TaskEx.WhenAll would return the array of Return statements, such that when every object gets finished, the array will be returned.

But it is not so. When I do :

    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));
        }

    }

I see my MessageBox appears more than once, and also await steps in with array of 1 element, then array of 2 element and so on.

Can anyone tell me what exactly the nature of TakEx.WhenAll?


The call to TaskEx.WhenAll occurs inside the for loop. You have to put it outside.

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

    }


WhenAll() create a tasks that completes when all the sub tasks complete. So, the method itself will not complete, but the task will.

It is a method that creates a new task that aggregates the separate task into a new, larger task.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜