创建新的cosmos DB时,Azure中会显示一些代码示例。大多数代码都能正常工作。但是我有一个单一的函数,它在执行时会冻结/挂起。有什么想法如何解决或排除故障吗?
代码:
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;
}
调用函数:
return await ItemsRepo.GetItemsAsync(p=>p.RunId == runId, "files-and-folders-with-unique-permissions");
最后是Windows应用:
var items = _db.GetFilesAndFoldersWithUniquePermissions(txtRunId.Text).Result;
完整代码:
存储库:
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");
}
应用程序:
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");
}
答案 0 :(得分:0)
混合 async-await 和.Result
阻止调用会导致死锁。
在这种情况下,事件处理程序允许使用async void
。
引用Async/Await - Best Practices in Asynchronous Programming
所以我建议您将应用重构以在事件处理程序中等待
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");
}
以使代码按预期方式流动。