简体   繁体   中英

HttpClient.PostAsync knocks out the app with exit code 0

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();
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM