Question

When executing this simple little test on Mono (3.2.1) on Mac OS X it never prints any response to the console but instead says Shutting down finalizer thread timed out.
Is there something wrong with this code or is my Mono misbehaving?

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);
        }
    }
}
Was it helpful?

Solution

You should almost never use async void methods and this is one reason why. Your Main() will end before HttpClientCall() actually completes. And since exiting from Main() terminates the whole application, nothing will get printed.

What you should do is to change your method into async Task and Wait() for it in your Main(). (Mixing await and Wait() can often lead to deadlocks, but it's the right solution for console applications.)

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top