用Csharp写一个多线程并发网络请求
时间: 2023-05-25 08:01:57 浏览: 214
下面是用 C# 实现的一个多线程并发网络请求的示例代码:
```
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConcurrentNetworkRequests
{
class Program
{
static void Main(string[] args)
{
int numOfThreads = 5;
Task[] tasks = new Task[numOfThreads];
for (int i = 0; i < numOfThreads; i++)
{
tasks[i] = Task.Run(() => SendRequest("https://www.example.com"));
}
Task.WaitAll(tasks);
}
static async Task SendRequest(string url)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response: " + responseBody);
}
}
}
}
```
这段代码中使用了 `Task.Run` 方法创建了多个线程并发执行网络请求,`Task.WaitAll` 方法等待所有任务完成,`SendRequest` 方法中使用了 `HttpClient` 类进行网络请求。
阅读全文