简体   繁体   中英

C# return from async task not working

I'm working on an async http call using HttpClient. The call is made inside an async task. The call is successful and I get a response from the Http call. But when I try to return the response from the task nothing happens, even though I have a breakpoint waiting after the return.

public void ExecuteTask(Foundation.Security.SecurityToken token, Order order)
{
    ExecuteTaskAsync(token, order).Wait();
}

public async Task ExecuteTaskAsync(Foundation.Security.SecurityToken token, Order order)
{
    if (order != null)
    {
        log.Info("Starting export of order " + order.ID.ToString());
        bool success = await ExportOrder(order, token);
        if (!success)
        {
            log.Error("Failed to export order with ID " + order.ID.ToString());
        }
    }
}

private async Task<bool> ExportOrder(Order order, Foundation.Security.SecurityToken token)
{
    try
    {
        ResponseObject response = await webService.SendOrder(new SenderInformation(token), new ReceiverInformation(order, token));
        if (response.Success && response.Status.Equals("201", StringComparison.OrdinalIgnoreCase))
        {
            log.Info(String.Format("Order ({0}) was successfully exported"), order.ExternalOrderID);
           return true;
    }
        return false;
    }
    catch (Exception e)
    {
        log.Error(String.Format("Exception occured while exporting order ({0})", order.ID), e);
        return false;
    }
}

Below is the code which does the actual http call. I marked the last functional line with the comment "The code successfully reach this line. After this nothing happens"

public Task<ResponseObject> SendOrder(SenderInformation sender, ReceiverInformation receiver)
{
    OrderRequest request = new OrderRequest(sender, receiver);
    return ExecuteRequest<OrderRequest, ResponseObject>(request);
}

private async Task<ResponseType> ExecuteRequest<RequestType, ResponseType>   (RequestType request)
where RequestType : RequestObject
where ResponseType : class, ResponseObject, new() 
{
    try
    {
        using (var client = new HttpClient())
        {
            string xml = SerializeRequest(request);
            HttpContent content = new StringContent(xml);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/xml");
            string requestUrl = "URL";
            HttpResponseMessage response = await client.PostAsync(requestUrl, content).ConfigureAwait(false);

            // Parse response
            if (response.IsSuccessStatusCode)
            {
                Stream responseStream = await response.Content.ReadAsStreamAsync();
                ResponseType responseObject = DeserializeResponse<ResponseType>(responseStream);
                if (responseObject != null)
                {
                    responseObject.Success = true;
                    return responseObject;  //The code successfully reach this line. After this nothing happens
                }
                else
                {
                    log.Error("Response could not be deserialized");
                }
            }
            else
            {
                log.Error("Error during request, got status code " +  response.StatusCode);
            }
        }
    }
    catch (Exception e)
    {
        log.Error("Something went wrong!", e);
    }
    return new ResponseType() { Success = false };
}

The problem is on this line:

ExecuteTaskAsync(token, order).Wait();

This causes a deadlock: the await s in the called method can't resume because the UI thread is blocked.

When you use async code, you must use it all the way; never wait synchronously for an async task to complete.

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