Asynchronous handler completed while asynchronous operation was pending - C #

0

Hello, I have some questions regarding the code below.

  • The code returns the following error [InvalidOperationException]: Module or asynchronous handler completed while the asynchronous operation was pending.
  • The main method that calls this task (this other methods) returns an IHttpActionResult and the response of the SMSAsync method ends up interfering with the response of my main method, ie I would like to return status 200 even with error in the SMS method - I already tried try cath without any action on cath ;
  • The first item, I solved using the call of this method with a Task.Factory.StartNew , since in this case, I do not need the answer of the method to follow but what if this were not the case?

    public async void SMSAsync(String mobileNumber)
    {
    
      Guid gui = Guid.NewGuid();
    
      using (var httpClient = new HttpClient())
      {
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization", "Basic XPTO");               
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
    
        using (var content = new StringContent("{  " +
            "\"sendSmsRequest\": {    " +
            "\"from\": \"WeBlank\",    " +
            "\"to\": \"55" + mobileNumber + "\",    " +
            "\"schedule\": \"2014-08-22T14:55:00\",    " +
            "\"msg\": \"Aqui vai a mensagem de SMS.\",    " +
            "\"callbackOption\": \"NONE\",    " +
            "\"id\": " +
            "\"" + gui.ToString() + "\", "     +
            "\"aggregateId\": \"1111\",    " +
            "\"flashSms\": false  }}", System.Text.Encoding.UTF8, 
            "application/json"))
    
        {
          using (var response = await httpClient.PostAsync("https://api-rest.zenvia360.com.br/services/send-sms", content))
          {
              string responseData = await response.Content.ReadAsStringAsync();
          }
        }
      }
    }
    

    link

    How do I call the method

    public IHttpActionResult CreateUser(ParticipanteCreateModel participante)
    {
       // código que executa a criação do usuário
       String telefone;
       telefone = part.Telefone.Replace('-', ' ');
       telefone = telefone.Replace('(', ' ');
       telefone = telefone.Replace(')', ' ');
       telefone = telefone.Replace(" ", String.Empty);
       Task.Factory.StartNew(() => SMSAsync(telefone)); 
    
       return Ok(usuarioId);
    
    }
    
        
    asked by anonymous 15.05.2018 / 17:49

    0 answers