首页 > 解决方案 > C#等待所有线程完成执行

问题描述

我正在使用多线程来获取 7 天的数据,生成 7 个线程,以便每个线程将获取一天的数据。

为什么是多线程?HttpResponseMessage 不能容纳超过 2GB 的数据

我想显示所有线程获取的总音量。如何等待所有线程完成?

class Program
    {
        static long totalVolume = 0;
        public static void CallToChildThread(String from, String to)
        {
            var httpclient = new HttpClient();
            String body = query;
            var webRequest = new HttpRequestMessage(HttpMethod.Post, api-url){Content = new StringContent(body, Encoding.UTF8, "application/json")};
            try
            {
                var response = httpclient.Send(webRequest);
                long size = (long)response.Content.Headers.ContentLength;
                totalVolume = totalVolume + size;
            }
            catch(Exception ex)
            {
                Console.WriteLine("Exception occured: for "+ from+"-"+to+" , " + ex.Message);
            }
        }
        static void Main(string[] args)
        {
            to = today;
            from = today - 1;
            count = 7;
            for (int i = 0; i <= count; i++)
            {
                Thread thread = new Thread(() => CallToChildThread(from, to));
                thread.Start(); 
                to = from;
                from = to-1;
            }

            //Code to wait for the completion of all the threads

            Console.WriteLine("total Volume fetched is "+totalVolume); 
         }
    }

标签: c#multithreadinghttpresponse

解决方案


推荐阅读