可能重复:
How to limit the amount of concurrent async I/O operations?
假设我有一个字符串数组
string[] domains = { "domain1.com", "domain2.com" ,..., "domain100.com"};
我想编写一个使用5个线程向这些域发送请求的应用程序,并按启动顺序将响应头保存到同一个日志文件中。例如:
Thread 1
domain1.com
Response header
Thread 2
domain2.com
Response header
Thread 3
domain3.com
Response header
Thread 4
domain4.com
Response header
Thread 5
domain5.com
Response header
Thread 1
domain6.com
Response header
Thread 2
domain7.com
Response header
我是编程多线程的新手,所以希望你能帮助我。非常感谢
答案 0 :(得分:2)
你不需要太在意多少线程创建的线程,线程池通过优化线程创建来照顾你,你的代码可能看起来像:
string[] domains = { "domain1.com", "domain2.com",...., "domain100.com" };
var client = new HttpClient();
var tasks = domains.Select(domain => client.GetAsync(domain)
.ContinueWith(task =>
{
HttpResponseMessage response = task.Result;
var headers = response.Headers;
//Write to log file
}));
await Task.WhenAll(tasks);
答案 1 :(得分:1)