我在多线程WebRequests上遇到了一些困难,我想通过使用以下代码在URL上执行100个get请求:
static void Main(string[] args)
{
for (int i = 0; i <= 100; i++)
{
Console.WriteLine("RUN TASK: " + i);
Task.Run(() =>
{
makeRequest();
});
}
Console.Read();
}
public static void makeRequest()
{
string html = string.Empty;
string url = @"https://192.168.205.50/api/v1/status";
Console.WriteLine("GET ON:" + url);
ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 1000;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ServicePoint.ConnectionLimit = 1000;
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
Console.WriteLine("Got response");
html = reader.ReadToEnd();
}
}
URL的睡眠时间为30秒:代码只会一次打开一次URL,而不是一次打开100个URL。
亲自,当我必须执行大量的http请求时,我会使用异步/等待
var stringsToCall = /* list/enumerable of uris */
HttpClient client = new HttpClient(); // Don't declare this locally, and only use an instance. Leaving it here for simplicity.
return await Task.WhenAll(urlsToCall.Select(url => client.GetAsync(url)));
这将为我们的HTTP调用创建一系列任务,并允许我们一次发送许多任务。如果您有兴趣,请阅读异步/等待。