37

Everything was working today until it stopped... Below is the minimum source code (I'm using VS 2012 Update 1, .Net 4.5). When I run it, app exits upon calling client.PostAsync() and so it never reaches Console.ReadLine(). Same in debugger, no exception, nothing, exit code 0.

I tried rebooting machine, restarting VS2012 - nothing works.

Again, everything was running today, not sure what changed (no software has been installed etc, all other network apps still work).

Any ideas? I think I'm loosing my mind.

class Program
{
    static void Main(string[] args)
    {
        Run();
    }

    private async static void Run()
    {
        using (var client = new System.Net.Http.HttpClient())
        {
            var headers = new List<KeyValuePair<string, string>>
                              {
                                  new KeyValuePair<string, string>("submit.x", "48"),
                                  new KeyValuePair<string, string>("submit.y", "15"),
                                  new KeyValuePair<string, string>("submit", "login")
                              };

            var content = new FormUrlEncodedContent(headers);

            HttpResponseMessage response = await client.PostAsync("http://www.google.com/", content);

            Console.ReadLine();
        }
    }
}
ashutosh raina
  • 9,228
  • 12
  • 44
  • 80
Maxim
  • 962
  • 2
  • 9
  • 21

1 Answers1

71

Your problem is that a program normally exits when its Main() method finishes. And your Main() finishes as soon as you hit the await in Run(), because that's how async methods work.

What you should do is to make Run() into an async Task method and then wait for the Task in your Main() method:

static void Main()
{
    RunAsync().Wait();
}

private static async Task RunAsync()
{
    …
}

In C# 7.1+ you should use async Main instead:

static async Task Main()
{
    await RunAsync();
}

private static async Task RunAsync()
{
    …
}

Few more notes:

  1. You should never use async void methods, unless you have to (which is the case of async event handlers).
  2. Mixing await and Wait() in a GUI application or in ASP.NET is dangerous, because it leads to deadlocks. But it's the right solution if you want to use async in a console application.
svick
  • 236,525
  • 50
  • 385
  • 514
  • 8
    +1. As a tip, it's easier to do your top-level `try`/`catch` in `RunAsync` rather than `Main`, because `Task.Wait` will wrap exceptions in an `AggregateException`. – Stephen Cleary Jan 07 '13 at 02:40