[英]async/await deadlock without using Task.Result
I have a web api that is using async/await all the way down: 我有一个使用async / await的web api:
public class SampleController : ApiController
{
public async Task<IEnumerable<DocumentModel>> GetAll()
{
List<DocumentModel> modelItems = new List<DocumentModel>();
var response = await SearchDocumentsAsync();
var items = response.Results.ToList();
foreach(var document in documents)
{
var model = new DocumentModel()
{
Id = document.Id,
Name = document.Name
};
modelItems.Add(model);
}
return modelItems;
}
private Task<DocumentSearchResponse<Document>> SearchDocumentsAsync()
{
using (var searchClient = new SearchServiceClient(new SearchCredentials(searchServiceKey), searchServiceUri))
using (var indexClient = searchClient.Indexes.GetClient(indexName))
{
var parameters = new SearchParameters()
{
IncludeTotalResultCount = true
};
// call the Azure Search service
return indexClient.Documents.SearchAsync<Document>(search.Term, parameters);
}
}
}
I am not using .Wait()
or .Result
anywhere in the call stack. 我没有在调用堆栈中的任何地方使用.Wait()
或.Result
。 Is it still possible for code like this to deadlock? 像这样的代码仍然可能死锁吗? When I debug this code I seem to be experiencing one but for the life of me I can't figure out why. 当我调试这段代码时,我似乎遇到了一个但是对于我的生活,我无法弄清楚为什么。
I have used Postman to send a couple of requests and sometimes the response never comes back. 我使用Postman发送了几个请求,有时候响应永远不会回来。 If I press the pause button in the debugger it will show a line in green that says "This is the next statement to execute when this thread returns from the current function." 如果我按下调试器中的暂停按钮,它将显示一条绿色的行,表示“这是当该线程从当前函数返回时要执行的下一个语句。” It is not consistent where the code will be when I press the pause button, but it seems that every other request will be blocked once one of them gets blocked. 当我按下暂停按钮时代码的位置不一致,但似乎一旦其中一个请求被阻止,其他所有请求都将被阻止。
Can the code above deadlock? 上面的代码可以死锁吗?
In SearchDocumentsAsync
, you're immediately returning the task from SearchAsync
. 在SearchDocumentsAsync
,您将立即从SearchAsync
返回任务。
You should be awaiting this task to ensure indexClient
and searchClient
aren't disposed before the operation is complete. 您应该等待此任务以确保在操作完成之前不处理indexClient
和searchClient
。 These being disposed may be what is introducing a deadlock. 这些被处置可能是引入僵局的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.