ExecuteNextAsync freezes/hangs in Azure Cosmos DB [duplicate]

人盡茶涼 提交于 2019-12-13 04:40:59

问题


When you create a new cosmos DB some code samples are shown in Azure. Most of the code works. However I have this single function that just freezes/hangs when Executed. Any ideas how to solve or troubleshoot?

Code:

public async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate, string collection)
{
    IDocumentQuery<T> query = Client.CreateDocumentQuery<T>(
        UriFactory.CreateDocumentCollectionUri(DatabaseId, collection),
        new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true })
        .Where(predicate)
        .AsDocumentQuery();

    List<T> results = new List<T>();
    while (query.HasMoreResults)
    {
        try
        {
            var result = await query.ExecuteNextAsync<T>();
            results.AddRange(result);
        }
        catch(Exception ex)
        {

        }
    }

    return results;
}

Calling the function:

return await ItemsRepo.GetItemsAsync(p=>p.RunId == runId, "files-and-folders-with-unique-permissions");

Finally the windows app:

var items = _db.GetFilesAndFoldersWithUniquePermissions(txtRunId.Text).Result;

Full code:

Repository:

public async Task<IEnumerable<Item>> GetFilesAndFoldersWithUniquePermissions(string runId)
    {
        var collectionLink = UriFactory.CreateDocumentCollectionUri("kk-governance-reporting", "files-and-folders-with-unique-permissions");
        return await ItemsRepo.GetItemsAsync(p=>p.RunId == runId, "files-and-folders-with-unique-permissions");
    }

App:

private void BtnGenerateReport_Click(object sender, EventArgs e)
    {
        var items = _db.GetFilesAndFoldersWithUniquePermissions(txtRunId.Text).Result;

        string json = JsonConvert.SerializeObject(items.ToArray());
        json = JToken.Parse(json).ToString(Formatting.Indented);

        //write string to file
        System.IO.File.WriteAllText(@"c:\temp\unique-files-and-folders.txt", json);

        MessageBox.Show("Completed");
    }

回答1:


Mixing async-await and .Result blocking calls can cause deadlocks.

In this case, event handlers allow for async void.

Reference Async/Await - Best Practices in Asynchronous Programming

So I suggest you refactor the App to await in the event handler

private async void BtnGenerateReport_Click(object sender, EventArgs e) {
    var items = await _db.GetFilesAndFoldersWithUniquePermissions(txtRunId.Text); //<-- 

    string json = JsonConvert.SerializeObject(items.ToArray());
    json = JToken.Parse(json).ToString(Formatting.Indented);

    //write string to file
    System.IO.File.WriteAllText(@"c:\temp\unique-files-and-folders.txt", json);

    MessageBox.Show("Completed");
}

To allow the code to flow as expected.



来源:https://stackoverflow.com/questions/54023982/executenextasync-freezes-hangs-in-azure-cosmos-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!