gpt4 book ai didi

azure-cosmosdb - DocumentDB 调用挂起

转载 作者:行者123 更新时间:2023-12-04 22:45:44 24 4
gpt4 key购买 nike

我正在调用我的 DocumentDB 数据库来查询一个人。如果此人不在数据库中,我将尝试将该人插入到我的集合中。

当我检查集合时,我看到正在创建新的人,但我的代码似乎卡在我第二次调用以将人插入到集合中的地方。知道为什么我的代码挂了?我不包括所有的代码来节省空间,例如GetDatabaseAsync()、GetCollectionAsync() 等都在工作。

using (client = new DocumentClient(new Uri(endPointUrl), authorizationKey))
{
//Get the database
var database = await GetDatabaseAsync();

//Get the Document Collection
var collection = await GetCollectionAsync(database.SelfLink, "People");

string sqlQuery = "SELECT * FROM People f WHERE f.id = \"" + user.PersonId + "\"";

dynamic doc = client.CreateDocumentQuery(collection.SelfLink, sqlQuery).AsEnumerable().FirstOrDefault();

if (doc == null)
{
// User is not in the database. Add user to the database
try
{
**// This is where the code is hanging. It creates the user in my collection though!**
await client.CreateDocumentAsync(collection.DocumentsLink, user);
}
catch
{
// Handle error
}
}
else
{
// User is already in the system.
user = doc;
}
}

代码是否可能挂起,因为我正在尝试在同一个 USING 语句中查询和插入文档。

创建一个新的客户端实例并创建一个单独的块来处理文档 INSERT 对我来说是不是一个更好的主意?

最佳答案

如果对异步方法的调用挂起,通常是因为通过使用 .Wait() 或 .Result 而不是 await 调用它来同步调用它。您尚未显示您的调用代码,因此请在此处包含它。

选项 1 :
不要同步调用异步方法。这是正确的做法。

选项 2 :
如果您同步调用此方法,则应在对 DocDB 的异步调用中使用 .ConfigureAwait(false) 。尝试这个:

var database = await GetDatabaseAsync()**.ConfigureAwait(false)**;
...
var collection = await GetCollectionAsync(database.SelfLink, "People")**.ConfigureAwait(false)**;
...
await client.CreateDocumentAsync(collection.DocumentsLink, user)**.ConfigureAwait(false)**;

更多详情请访问 ConfigureAwait

关于azure-cosmosdb - DocumentDB 调用挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27083501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com