HttpClient.PostAsync doesn't work when awaited

RichardHopkinsRichardHopkins JPMember, University ✭✭✭

Can anyone explain the following?:

    HttpResponseMessage response = null;

    var jsonRequest = JsonConvert.SerializeObject(obj);

    try 
    {
        var content  = new StringContent(jsonRequest, Encoding.UTF8, "text/json");

        response = client.PostAsync(url, content).Result;

        //response = await client.PostAsync(url, content);

    }
    catch(Exception e)
    {
        Console.WriteLine(e.Message);
    }

The uncommented line (which blocks) works fine. The commented line, which awaits the response, hangs indefinitely. client is just a System.Net.Http.HttpClient.

Posts

  • mehmedmehmed USMember

    Hi Richard, Iis there a way tu await PostAsync?

  • JasonDiOrioJasonDiOrio USMember

    This article does a very good job explaining what happened to you: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

    In short, don't .Result or .Wait a Promise task (a Task returned by an "async" method containing an "await") because it will block the activation of the "await" in the calling context, where it is meant to resume.

  • Thanks Richard Hopkins. You saved my days

  • LeTapsLeTaps ZWMember

    HttpResponseMessage response = null; //Declaring an http response message

    var jsonRequest = JsonConvert.SerializeObject(obj);// converting the obj into  a JSON object
    
    try 
    {
        var content  = new StringContent(jsonRequest, Encoding.UTF8, "text/json");
    
        response = client.PostAsync(url, content).Result;// storing the results of posts in response
    
        //response = await client.PostAsync(url, content);
    
    }
    catch(Exception e)
    {
        Console.WriteLine(e.Message);
    }h
    
  • AndrewBensonAndrewBenson GBMember
    edited October 2017

    I had a blocking problem with my Task<> MakeRequest method.. it Posts a file and is supposed to assign a label with the response. This line was being called in a button click handler:

    MakeRequest(file).Wait();

    to fix it I had to change the method return type toTask<string>and use this line of code instead

    myLabel.Text = await MakeRequest(file);

  • @RichardHopkins said:
    Ok, discovered the answer the hard way after 2 days of tracing and breakpointing. In a nutshell, you can't call an asynchronous method

    await asyncmethod2()
    

    from a method that blocks

    method1().Result
    

    as it causes a deadlock to occur when method2 attempts to return execution to the caller.

    Worked for me too. Thanks

Sign In or Register to comment.