C#从异步任务返回不起作用

时间:2015-08-31 07:20:57

标签: c# .net asynchronous

我正在使用HttpClient处理异步http调用。该调用是在异步任务中进行的。呼叫成功,我从Http呼叫中得到响应。但是当我尝试从任务返回响应时,没有任何反应,即使我在返回后有一个断点等待。

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;
    }
}

以下是执行实际http调用的代码。我用注释&#34标记了最后一行功能;代码成功到达此行。在此之后没有任何事情发生&#34;

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 };
}

1 个答案:

答案 0 :(得分:2)

问题在于这一行:

ExecuteTaskAsync(token, order).Wait();

这会导致死锁:由于UI线程被阻止,被调用方法中的await无法恢复。

使用异步代码时,必须一直使用它;永远不要等待异步任务完成。