C# 如何使用.net内核中的httpclient获取异步/等待中的REST Get请求的运行时间
当我使用Task.Wait调用下面的DoRestCall方法时,经过的时间基本上显示为0 OK,显示为3ms。我知道这是因为异步/等待模式。我想知道完成rest通话的实际时间。我想不出一个办法进入HttpClient来解决这个问题C# 如何使用.net内核中的httpclient获取异步/等待中的REST Get请求的运行时间,c#,asp.net-core,.net-core,async-await,C#,Asp.net Core,.net Core,Async Await,当我使用Task.Wait调用下面的DoRestCall方法时,经过的时间基本上显示为0 OK,显示为3ms。我知道这是因为异步/等待模式。我想知道完成rest通话的实际时间。我想不出一个办法进入HttpClient来解决这个问题 public static async Task DoRestCall() { HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetA
public static async Task DoRestCall()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://http://myrest.com");
if (response.IsSuccessStatusCode)
{
var sw = new Stopwatch();
sw.Start();
var x = await response.Content.ReadAsStringAsync();
sw.Stop();
Console.WriteLine($"{x.Length} {sw.ElapsedMilliseconds}");
}
}
您应该移动秒表以同时包含.GetAsync调用
public static async Task DoRestCall()
{
HttpClient client = new HttpClient();
string responseBody = String.Empty;
var sw = new Stopwatch();
sw.Start();
HttpResponseMessage response = await client.GetAsync("https://http://myrest.com");
if (response.IsSuccessStatusCode)
{
responseBody = await response.Content.ReadAsStringAsync();
}
sw.Stop();
Console.WriteLine($"{responseBody.Length} {sw.ElapsedMilliseconds}");
}
您应该移动秒表以同时包含.GetAsync调用
public static async Task DoRestCall()
{
HttpClient client = new HttpClient();
string responseBody = String.Empty;
var sw = new Stopwatch();
sw.Start();
HttpResponseMessage response = await client.GetAsync("https://http://myrest.com");
if (response.IsSuccessStatusCode)
{
responseBody = await response.Content.ReadAsStringAsync();
}
sw.Stop();
Console.WriteLine($"{responseBody.Length} {sw.ElapsedMilliseconds}");
}
查看HttpClient运行时间的其他方法
1.更改为信息或跟踪
样本输出
info: System.Net.Http.HttpClient.MyClient.LogicalHandler[100]
Start processing HTTP request GET https://api.github.com/repos/aspnet/docs/branches
info: System.Net.Http.HttpClient.MyClient.ClientHandler[100]
Sending HTTP request GET https://api.github.com/repos/aspnet/docs/branches
info: System.Net.Http.HttpClient.MyClient.ClientHandler[101]
Received HTTP response after 682.9818ms - OK
info: System.Net.Http.HttpClient.MyClient.LogicalHandler[101]
End processing HTTP request after 693.1094ms - OK
2.创建新的
欲知详情
查看HttpClient运行时间的其他方法
1.更改为信息或跟踪
样本输出
info: System.Net.Http.HttpClient.MyClient.LogicalHandler[100]
Start processing HTTP request GET https://api.github.com/repos/aspnet/docs/branches
info: System.Net.Http.HttpClient.MyClient.ClientHandler[100]
Sending HTTP request GET https://api.github.com/repos/aspnet/docs/branches
info: System.Net.Http.HttpClient.MyClient.ClientHandler[101]
Received HTTP response after 682.9818ms - OK
info: System.Net.Http.HttpClient.MyClient.LogicalHandler[101]
End processing HTTP request after 693.1094ms - OK
2.创建新的
欲知详情
为什么你只在接到请求后才启动秒表?您正在计时ReadAsString部分。异步不是这里的问题,只是您放置秒表的位置。为什么您只在请求后启动秒表?您正在计时ReadAsString部分。异步不是这里的问题,只是你的秒表的位置。