Parallel ForEach not awaiting for HttpClient [duplicate]

孤街浪徒 提交于 2020-02-03 01:27:25

问题


In the code below (a fairly simple one just for demonstration), my finally clause gets executed when awaiting for the HttpClient to finish. So the output is something like:

Done

StatusCode: 200,...

When I was expecting it to be:

StatusCode: 200,...

Done

  class Program
        {
            private static HttpClient _httpClient = new HttpClient();
            static async Task Main(string[] args)
            {
                var numbers = new List<int> {1};
                try
                {
                    await Task.Run(() =>
                        {
                            Parallel.ForEach(numbers, async (number) => { await Do1(); });
                        });
                }
                finally
                {
                    Console.WriteLine("Done");
                }

                Console.ReadKey();
            }
            private static async Task Do1()
            {
                using (var result = await _httpClient.GetAsync("http://www.google.com"))
                {
                    Console.WriteLine(result);
                }
            }
            private static async Task Do2()
            {
                for (int i = 0; i <= 10; i++)
                {
                    Console.WriteLine("Doing" + await Multiply(i));
                }
            }

            private static async Task<int> Multiply(int number)
            {
                return await Task.FromResult(number * number);
            }
        }

If I replace my Main method to use the Do2 method then everything works as expected with the following output ("Done" gets printed at the very end):

.

.

.

Doing100

Done

So why is the HttpClient not working as I am expecting it to work? Something that I'd like to mention is that I would like to use the Parallel.ForEach instead of the Task.WhenAll function.

来源:https://stackoverflow.com/questions/59412905/parallel-foreach-not-awaiting-for-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!