异步调用从不 returns

Async call never returns

请看下面的代码。

public static class DbModel
{
        public static readonly int TableID = 0;

        static DbModel()
        {
            DbModel.PodID = FetchTableID().PodID;
        }

        public static Pod FetchTableID()
        {
            Pod result = null;
            try
            {                
        //Control never comes back from this line.  What am I missing?
                var searchResult = apiPod.SearchTableAsync(1).Result;
                result = searchResult.First();
            }
            catch (Exception ex)
            {
                Helpers.TraceException(PageName,"FEtchPodID","Unable to fetch PodID",ex);
            }
            return result;
        }
}

SearchTableAsync 的签名如下所示

public async Task<List<Pod>> SearchTableAsync(int i)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    //deleted - connecting to server, constructing query string etc.

                    var response = await client.GetAsync(ApiBaseUrl + "api/Pod/Search" + queryString);
                    if (response.IsSuccessStatusCode)
                    {
                        var podList = await response.Content.ReadAsAsync<List<Pod>>();
                        return podList;
                    }
                    else
                    {
                        //log error
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.TraceError(null, ex);
            }
            return null;
        }

对 SearchTableAsync 的调用永远不会 returns 返回。我错过了什么吗?还是因为我是从静态构造函数中调用它的?

searchResult = apiPod.SearchTableAsync(1).excute.get;

用这个代替

var searchResult = apiPod.SearchTableAsync(1).Result;

问题可能是由于使用了 Task.Result 属性。这是阻塞 属性,可能导致 deadlock。您可以简单地 await 将 return 结果的任务,但是您需要使方法 async.

    public static async Pod FetchTableID()
    {
        Pod result = null;
        try
        {                
            var searchResult = await apiPod.SearchTableAsync(1);
            result = searchResult.First();
        }
        catch (Exception ex)
        {
            Helpers.TraceException(PageName,"FEtchPodID","Unable to fetch PodID",ex);
        }
        return result;
    }

This post 解释了阻塞的原因。 干杯, 赫曼