Dis*_*ile 3 c# asynchronous async-await asp.net-web-api
我有一个使用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我没有使用.Wait()或.Result在调用堆栈中的任何位置.像这样的代码仍然可能死锁吗?当我调试这段代码时,我似乎遇到了一个但是对于我的生活,我无法弄清楚为什么.
我使用Postman发送了几个请求,有时候响应永远不会回来.如果我按下调试器中的暂停按钮,它将显示一条绿色的行,表示"这是当该线程从当前函数返回时要执行的下一个语句." 当我按下暂停按钮时代码的位置不一致,但似乎一旦其中一个请求被阻止,其他所有请求都将被阻止.
上面的代码可以死锁吗?
在SearchDocumentsAsync,你立即返回任务SearchAsync.
在操作完成之前,您应该等待此任务以确保indexClient并且searchClient不处理.这些被处置可能是引入僵局的原因.
| 归档时间: |
|
| 查看次数: |
377 次 |
| 最近记录: |