【问题标题】:Async call never returns异步调用永远不会返回
【发布时间】:2015-05-07 12:06:33
【问题描述】:

请看下面的代码。

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 的调用永远不会返回。我错过了什么吗?还是因为我从静态构造函数调用它?

【问题讨论】:

  • 这是什么类型的应用程序? WinForms、WPF 等。
  • 它是一个 WPF 应用程序...

标签: multithreading task-parallel-library async-await


【解决方案1】:

问题可能是由于使用了Task.Result 属性。这是一个阻塞属性,可能导致deadlock。您可以简单地 await 将返回结果的任务,但您需要创建方法 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;
    }

【讨论】:

    【解决方案2】:

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

    用这个代替

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

    【讨论】:

    • 谢谢,但我在 SearchTableAsync(1) 方法调用中看不到任何名为“Execute”的方法/属性...
    • 你可以发布你的方法 searchtableasync。
    【解决方案3】:

    This 帖子解释了它被阻止的原因。 干杯, 赫曼特

    【讨论】:

      猜你喜欢
      • 2016-01-16
      • 2017-07-13
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 2017-12-06
      相关资源
      最近更新 更多