none
How to Return and Get from async Task? RRS feed

  • Question

  • Hi,

    I am trying to use async Task to send email and return the status code but straggling and need help please..

    async Task<HttpStatusCode> SendMessage()
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes("api" + ":" + "key-xxxxxxxxxxxxxxxxxx")));
    
    
        var form = new Dictionary<string, string>();
        form["from"] = "sender@softnames.com";
        form["to"] = "goto@softnames.com";
        form["subject"] = "Test";
        form["text"] = "testing testing...";
    
        var response = await client.PostAsync("https://api.mailgun.net/v2/" + "domain.softnames.com" + "/messages", new FormUrlEncodedContent(form));
    
        return response.StatusCode;
    }

    and here I am trying to get the status code:

    void btnSendMessage_Clicked(object sender, System.EventArgs e)
    {
        if (SendMessage() == HttpStatusCode.OK)
        {
            // status is OK;
        }
        else
        {
            // status is NOT ok;
        }
    }

    I am getting this: error:

    /Users/jassim/Projects/Adel_Al_Asoomi/Adel_Al_Asoomi/Pages/Contact.xaml.cs(17,17): Error CS0019: Operator '==' cannot be applied to operands of type 'Task<HttpStatusCode>' and 'HttpStatusCode' (CS0019) (Adel_Al_Asoomi)

    Kindly help..

    Thanks,

    Jassim


    Saturday, November 4, 2017 6:46 PM

All replies

  • In order to solve the compilation error only, try this:

       var r = SendMessage().Result;
       if( r == HttpStatusCode.OK )
       {       . . .

     

    But consider the next approach too:

       async void btnSendMessage_Clicked( object sender, System.EventArgs e)
       {
          var r = await SendMessage();
          if( r == HttpStatusCode.OK )
          {
             . . .

    Saturday, November 4, 2017 8:29 PM