我在多線程中使用HttpClient時遇到了一些麻煩。.NET HttpClient多線程
如果我同時推出很多下載,每個線程的第一下載速度很慢(與並行線程增加)
舉例來說,如果我有一個線程,一切都很好
First download Elapsed Time Download: 197 ms
Second download Elapsed Time Download: 171 ms
但有一個線程,下載時間增加
First download Elapsed Time Download: 3881 ms
...
Second download Elapsed Time Download: 96 ms
...
網絡帶寬是不是一個問題,我有同樣的問題localhost。
下面是一些代碼來重現問題:
static void Main(string[] args)
{
ServicePointManager.DefaultConnectionLimit = 200;
List<Task> tasks = new List<Task>();
for (var i = 0; i < 10; i++)
{
tasks.Add(
Task.Factory.StartNew(() =>
{
Stopwatch s = Stopwatch.StartNew();
HttpClient httpClient = new HttpClient();
HttpResponseMessage httpDownloadResponse = httpDownloadResponse = httpClient.GetAsync("http://www.google.fr/", HttpCompletionOption.ResponseHeadersRead).Result;
s.Stop();
Console.WriteLine("First download Elapsed Time Download: {0} ms", s.ElapsedMilliseconds);
s = Stopwatch.StartNew();
httpClient = new HttpClient();
httpDownloadResponse = httpClient.GetAsync("http://www.google.fr/", HttpCompletionOption.ResponseHeadersRead).Result;
s.Stop();
Console.WriteLine("Second download Elapsed Time Download: {0} ms", s.ElapsedMilliseconds);
})
);
}
Task.WaitAll(tasks.ToArray());
while (Console.ReadLine() != null) ;
}
@Adriano - '控制檯'是線程安全的,並且不包括在計時中。 –
@BrianReischl我的壞! –
它可能是相關的(或可能不相關),但.net觀察到的約定是隻有三個到同一個URL的Http連接被允許來自特定的客戶端操作系統。這在ServicePointManager.DefaultConnectionLimit中定義。這是在這裏討論http://stackoverflow.com/questions/866350/how-can-i-programmatically-remove-the-2-connection-limit-in-webclient,並可能導致你觀察並行http活動戲劇性放緩在同一個網址上。 – PhillipH