【问题标题】:why await does not wait untill httpclient postasync complets?为什么 await 不等到 httpclient postasync 完成?
【发布时间】:2020-06-30 05:06:45
【问题描述】:

我正在创建 http 客户端以使用一些 api。

这是我调用 api 端点的客户端方法。

public async Task<HttpResponseMessage> SendRequestAsync()
        {

            string adaptiveUri = "https://some-api/api/Authentication/AuthenticateThirdPartyUserAsync";

            using (HttpClient httpClient = new HttpClient())
            {
                var json = JsonConvert.SerializeObject(new { userName = "uname", password = "123", applicantCode = "hello" });
                var payload = new StringContent(json, Encoding.UTF8, "application/json");

                HttpResponseMessage responseMessage = null;
                try
                {
                    responseMessage = await httpClient.PostAsync(adaptiveUri, payload);
                }
                catch (Exception ex)
                {
                    if (responseMessage == null)
                    {
                        responseMessage = new HttpResponseMessage();
                    }
                    responseMessage.StatusCode = HttpStatusCode.InternalServerError;
                    responseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
                }
                return responseMessage;
            }
        }

调用方法如下

public async Task<IBaseStatus> Handle(InspectionAddedEvent domainEvent)
{
   var tk = await _iAClient.SendRequestAsync();
   return something;
}

但await 不会等到 postasync 完成。

但是当我使用

httpClient.PostAsync(adaptiveUri, payload).GetAwaiter().GetResult()

它会等到帖子完成。

有人知道吗?

谢谢。

【问题讨论】:

  • 不等到完成是什么意思?你怎么知道它没有完成?
  • 请查看minimal reproducible example 发布代码指南和edit 问题以显示重现错误行为的所有必要代码 - 到目前为止,帖子中显示的代码是进行异步调用和没有理由相信它会按照您描述的方式行事。您可能希望完全删除所有异常处理(除非它是您的同步路径进入的地方 - 即无效的 DNS 名称可以使此代码同步失败)

标签: c# async-await xmlhttprequest httpclient httpresponse


【解决方案1】:

await _iAClient.SendRequestAsync(); 肯定会等待PostAsync。

我认为问题在于您在SendRequestAsync 中收到异常并混淆了结果。

完全删除try/carch 块

public async Task<HttpResponseMessage> SendRequestAsync()
{
    string adaptiveUri ="https://someapi/api/Authentication/AuthenticateThirdPartyUserAsync";

    using (HttpClient httpClient = new HttpClient())
    {
        var json = JsonConvert.SerializeObject(new { userName = "uname", password = "123", applicantCode = "hello" });
        var payload = new StringContent(json, Encoding.UTF8, "application/json");
        return await httpClient.PostAsync(adaptiveUri, payload);                
    }
}

并尝试在调用者中捕获它:

public async Task<IBaseStatus> Handle(InspectionAddedEvent domainEvent)
{
    try 
    {
        var tk = await _iAClient.SendRequestAsync();
        return something;
    }
    catch(Exception ex)
    {
        //Probably return some IBaseStatus
    }       
}

【讨论】:

  • 没有机会,我从静态类调用是等待的效果吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 2018-07-02
  • 2012-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-16
相关资源
最近更新 更多