请看下面的代码。
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永远不会返回。我错过了什么吗?或者因为我从静态构造函数中调用它?
答案 0 :(得分: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;
}
答案 1 :(得分:0)
searchResult = apiPod.SearchTableAsync(1).excute.get;
使用此代替
var searchResult = apiPod.SearchTableAsync(1).Result;
答案 2 :(得分:0)
This帖子解释了为何阻止它。 干杯, 与Hemant