gpt4 book ai didi

c# - 并行运行时如何获取HttpClient响应时间

转载 作者:太空狗 更新时间:2023-10-29 18:29:27 26 4
gpt4 key购买 nike

在我的 ASP.NET MVC4 应用程序中,我有一个 Controller 操作,我可以在其中访问多个外部网站并收集我以聚合方式显示在我的页面上的信息。显然,我想并行执行此操作,因此我编写了与此类似的代码:

var client1 = new HttpClient().GetAsync("http://google.com");
var client2 = new HttpClient().GetAsync("http://stackoverflow.com");
var client3 = new HttpClient().GetAsync("http://twitter.com");

var result1 = client1.Result;
var result2 = client2.Result;
var result3 = client3.Result;

我如何才能知道每个请求需要多长时间才能完成,以便我可以在我的页面上显示该信息?

最佳答案

我可能会尝试以下操作:

private async void _HttpServerDemo()
{
var info1 = _GetHttpWithTimingInfo("http://google.com");
var info2 = _GetHttpWithTimingInfo("http://stackoverflow.com");
var info3 = _GetHttpWithTimingInfo("http://twitter.com");

await Task.WhenAll(info1, info2, info3);
Console.WriteLine("Request1 took {0}", info1.Result);
Console.WriteLine("Request2 took {0}", info2.Result);
Console.WriteLine("Request3 took {0}", info3.Result);
}

private async Task<Tuple<HttpResponseMessage, TimeSpan>> _GetHttpWithTimingInfo(string url)
{
var stopWatch = Stopwatch.StartNew();
using (var client = new HttpClient())
{
var result = await client.GetAsync(url);
return new Tuple<HttpResponseMessage, TimeSpan>(result, stopWatch.Elapsed);
}
}

关于c# - 并行运行时如何获取HttpClient响应时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14177725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com