在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);
}
}
}
答案 0 :(得分:7)
你几乎不应该使用async void
方法,这就是原因之一。您的Main()
将在HttpClientCall()
实际完成之前结束。由于退出Main()
会终止整个应用程序,因此不会打印任何内容。
您应该在async Task
中将方法更改为Wait()
和Main()
。 (混合使用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);
}
}