我的 wpf 程序从文本文件中读取命令,然后通过 HttpClient 发送这些命令。 每个 GetAsync 响应大约需要 2 秒才能完成。这似乎太长了,尤其是当我要发送 50 个命令时。
这是 HttpClient 发送/接收 GetAsync 消息的正常时间吗?有更快的方法吗?
static readonly HttpClient client = new HttpClient();
public MainWindow()
{
InitializeComponent();
}
private async void Register_ClickAsync(object sender, RoutedEventArgs e)
{
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader(@"C\path.txt");
while ((line = file.ReadLine()) != null)
{
try
{
var watch = Stopwatch.StartNew();
HttpResponseMessage response = await client.GetAsync(line);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
watch.Stop();
var elapsedMS = watch.ElapsedMilliseconds;
RequestTextBox.Text += "\n" + elapsedMS;
}
catch (HttpRequestException ex)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", ex.Message);
this.RequestTextBox.Text += ("\n" + "Message: {0} ", ex.Message);
}
}
file.Close();
}
}
更新: 这个原始程序是一个 .net Core WPF 应用程序。我使用完全相同的代码创建了一个 .net 框架 WPF 应用程序。 .net 框架应用程序需要 2000 毫秒来发送第一个 HttpClient GetAsync 命令,然后 <10 毫秒用于后续命令。这是一个巨大的性能提升。有人有解释吗?我一直找不到任何解释这一点的文章。
最佳答案
您的代码正在等待每个请求。
您可以通过调用 GetAsync
创建许多任务,然后使用 Task.WhenAll()
等待它们。速度会更快。
关于c# - HttpClient GetAsync 大约需要 2 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60100617/