c# - 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# - 如何在 C# 中正确解密存储在 SQL Server 数据库中的密码
- angular - 级联两个 observables 并以 angular 和 firebase 返回一个 ng-container 列表
- javascript - DiscordAPIError:无效的表单正文 embed.image.url:不支持方案“[对象响应]”。方案必须是 ('http', 'https') 之一
- apache - Apache Web 服务器日志中的 HTTP CONNECT 请求
- java - 过滤自定义数据类型的来源
- docker - jib-maven-plugin - 如何设置文件夹权限
- go - goroutine 和 Waitgroup 的问题
- c# - 如何在wpf中绑定具有应用样式的文本框
- angular - 类型'可观察的
' 不可分配给类型 'Observable ' - git - git clone、git fetch 和 git pull 有什么区别?