我想同步使用HttpClient,但是當我做出許多併發請求時,它停止工作。我寫了兩個測試,一個用於異步使用,一個用於同步使用。 TestMethod
總是在4秒後返回響應。異步測試正常工作。幾乎所有的請求都在同步測試中超時,最後的請求只有20個成功。我嘗試使用單個HttpClient
來請求併爲每個新請求創建新的HttpClient
實例。沒有不同。可能它與this deadlock有關。同步併發HttpClient使用
我正在使用VS2013和.NET Framework 4.5.1,目標是Framework 4.5。我通過NuGet獲得HttpClient:<package id="Microsoft.Net.Http" version="2.2.15" targetFramework="net45" />
我不想異步使用HttpClient
,因爲這意味着我必須重寫我的整個應用程序。任何想法我在這裏做錯了什麼?
// all 800 requests complete successfully
[Test]
public async void Asyncmethod()
{
var sw = new Stopwatch();
sw.Start();
var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(15);
var tasks = Enumerable.Range(0, 800).Select(x => Task.Run(async() =>
{
try
{
var swx = new Stopwatch();
swx.Start();
var response = await client.GetStringAsync("http://localhost:7002/TestMethod").ConfigureAwait(false);
swx.Stop();
Console.WriteLine(x + " " + response + " in " + swx.ElapsedMilliseconds + " ms.");
}
catch (Exception e)
{
Console.WriteLine(x + " Exception: " + e.Message);
}
})).ToArray();
await Task.WhenAll(tasks);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
// almost all of 800 requests time out
[Test]
public void Syncmethod()
{
var sw = new Stopwatch();
sw.Start();
var client = new HttpClient();
var tasks = Enumerable.Range(0, 800).Select(x => Task.Run(() =>
{
try
{
var swx = new Stopwatch();
swx.Start();
var response = client.GetStringAsync("http://localhost:7002/TestMethod");
if (response.Wait(15000))
{
swx.Stop();
Console.WriteLine(x + " " + response.Result + " in " + swx.ElapsedMilliseconds + " ms.");
}
else
{
swx.Stop();
Console.WriteLine(x + " timed out.");
}
}
catch (Exception e)
{
Console.WriteLine(x + " Exception: " + e.Message);
}
})).ToArray();
foreach (var task in tasks)
task.Wait(60000);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
首先,在您的示例中,如果請求足夠長,則任務將在請求完成之前完成。其次,我將如何編寫一個函數,使用'ContinueWith'來返回響應內容? – Thresh
已更新。但是您必須重寫您的代碼才能使用任務而無需等待。 –
sh1ng