Mono上的简单HttpClient测试失败
本文关键字:测试 失败 HttpClient 简单 Mono | 更新日期: 2023-09-27 18:26:47
当在Mac OS X上的Mono(3.2.1)上执行这个简单的小测试时,它从不向控制台打印任何响应,而是说Shutting down finalizer thread timed out.
这段代码有什么问题吗?或者我的Mono行为不端?
using System;
using System.Net.Http;
namespace VendTest
{
class MainClass
{
public static void Main(string[] args)
{
Client client = new Client();
client.HttpClientCall();
}
}
public class Client
{
HttpClient client;
public Client()
{
client = new HttpClient();
}
public async void HttpClientCall()
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync("http://vendhq.com");
string responseAsString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseAsString);
}
}
}
您几乎不应该使用async void
方法,这也是原因之一。您的Main()
将在HttpClientCall()
实际完成之前结束。由于从Main()
退出会终止整个应用程序,因此不会打印任何内容。
您应该做的是将方法更改为async Task
,并在Main()
中为其更改Wait()
。(混合使用await
和Wait()
通常会导致死锁,但这是控制台应用程序的正确解决方案。)
class MainClass
{
public static void Main()
{
new Client().HttpClientCallAsync().Wait();
}
}
public class Client
{
HttpClient client = new HttpClient();
public async Task HttpClientCallAsync()
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync("http://vendhq.com");
string responseAsString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseAsString);
}
}