Malin
Malin

Reputation: 105

Trying to understand Async/Await but seem to get deadlock c#

I have an async method, and from within that method I call another Async method. In the second method I call an API. I know that my API request is correct, so it has something to do with the async/await.

Am I creating a deadlock? If so where? And how to fix it?

public async Task<AmountInvoicedModel> CreatePaymentsAndSendAsEmail(InvoiceRequestModel model, bool calculate)
    {
      ....
      await CreateQRCodes("testMsg");
      ....
    }

public async Task CreateQRCodes(string ocrNmbr)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("https://mpc.getswish.net/qrg-swish/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        var json = new
        {
            payee = new
            {
                value = "01234567890",
                editable = false
            },
            amount = new
            {
                value = 100,
                editable = false
            },
            message = new
            {
                value = $"{ocrNmbr}",
                editable = false
            },
            format = "jpg",
            size = 300
        };
        try
        {
            HttpResponseMessage response = await client.PostAsJsonAsync(
            "api/v1/prefilled", json);

            var result = await response.Content.ReadAsStreamAsync();
        }
        catch (Exception ex)
        {
            throw;
        }
        

        
    }

UPDATE: I had to put await on the "CalculateInvoice" method too. So now it doesnt deadlock anymore, it moves on - but without giving me a response

[HttpPost]
    [Route("calculateInvoice")]
    public async Task<IHttpActionResult> CalculateInvoice([FromBody] InvoiceRequestModel model)
    {
        model.EmailAddress = AccountHelper.GetLoggedInUsername();
        var result = await _paymentHandler.CreatePaymentsAndSendAsEmail(model, true);
        if (result == null)
            return Conflict();
        return Ok(result);
    }

Upvotes: 0

Views: 231

Answers (1)

Malin
Malin

Reputation: 105

I had to put await on the CalculateInvoice method for it to move on.

[HttpPost]
[Route("calculateInvoice")]
public async Task<IHttpActionResult> CalculateInvoice([FromBody] InvoiceRequestModel model)
{
    model.EmailAddress = AccountHelper.GetLoggedInUsername();
    var result = await _paymentHandler.CreatePaymentsAndSendAsEmail(model, true);
    if (result == null)
        return Conflict();
    return Ok(result);
}

Upvotes: 1

Related Questions