C#Async/Await呼叫无法正常工作

Dea*_*and 0 .net c# asynchronous async-await

我试图从同步方法调用异步方法,它继续轰炸调用GetUsTraceApiHealth()但没有错误.问题是什么?

通话方式:

public ActionResult TestSSN()
{
    try
    {
        var apiResponse = GetUsTraceApiHealth().GetAwaiter().GetResult();
        string responseBody = apiResponse.Content.ReadAsStringAsync().Result;
        return Json(responseBody, JsonRequestBehavior.AllowGet);
    }
    catch (Exception e)
    {                    
        throw new Exception(e.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

被调用的方法:

public async Task<HttpResponseMessage> GetUsTraceApiHealth()
{
    using (HttpClient httpClient = new HttpClient())
    {
        try
        {
            string uri = $"https://trace.{ConfigHelper.SterlingDomain}health?deep";

            HttpResponseMessage apiResponse = await httpClient.GetAsync(uri);
            return apiResponse;
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 5

遵循"异步一直向下"的异步口号.基本上,你几乎不应该打电话.Result给任务.在大多数情况下,您的调用方法也应该是异步的.然后你可以简单地等待操作的结果:

public async Task<ActionResult> TestSSN()
{
    //...
    var apiResponse = await GetUsTraceApiHealth();
    string responseBody = await apiResponse.Content.ReadAsStringAsync();
    //...
}
Run Code Online (Sandbox Code Playgroud)

应该由顶层的应用程序主机(在本例中为ASP.NET和Web服务器)来处理同步上下文.您不应该尝试将异步操作屏蔽为同步操作.