问题
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