async / await deadlock而不使用Task.Result

时间:2015-12-17 19:56:34

标签: c# asynchronous asp.net-web-api async-await

我有一个使用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);
        }
    }    
}

我没有在调用堆栈中的任何位置使用.Wait().Result。像这样的代码仍然可能死锁吗?当我调试这段代码时,我似乎遇到了一个但是对于我的生活,我无法弄清楚为什么。

我使用Postman发送了几个请求,有时候响应永远不会回来。如果我按下调试器中的暂停按钮,它将显示一条绿色的行,表示“这是当该线程从当前函数返回时要执行的下一个语句。”当我按下暂停按钮时,代码的位置不一致,但似乎一旦其中一个请求被阻止,其他所有请求都将被阻止。

上面的代码可以死锁吗?

1 个答案:

答案 0 :(得分:5)

SearchDocumentsAsync中,您立即从SearchAsync返回任务。

您应该等待此任务,以确保在操作完成之前处置indexClientsearchClient。这些被处置可能是引入僵局的原因。

相关问题