3

在 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);
        }
    }
}
4

1 回答 1

7

您几乎不应该使用async void方法,这就是原因之一。你的遗嘱在实际完成Main()之前就结束了。HttpClientCall()而且由于退出Main()会终止整个应用程序,因此不会打印任何内容。

您应该做的是将您的方法更改为async TaskWait()在您的Main(). (混合awaitWait()经常会导致死锁,但它是控制台应用程序的正确解决方案。)

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);
    }
}
于 2013-08-08T10:13:37.097 回答