在 C# 中异步创建新的 DocumentDB 文档的问题
本文关键字:DocumentDB 文档 问题 创建 异步 | 更新日期: 2023-09-27 18:34:25
我刚开始使用DocumentDB,所以我下载了.NET SDK。按照从 Azure 网站下载的使用示例,我正在尝试创建一些文档以保存到 DocumentDB。示例代码如下
public static void Main(string[] args)
{
try
{
GetStartedDemo().Wait();
}
catch (DocumentClientException de)
{
// omissis
}
}
private static async Task GetStartedDemo()
{
var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);
Family andersonFamily = new Family
{
Id = "AndersenFamily",
LastName = "Andersen",
Parents = new Parent[] {
new Parent { FirstName = "Thomas" },
new Parent { FirstName = "Mary Kay"}
},
Children = new Child[] {
new Child
{
FirstName = "Henriette Thaulow",
Gender = "female",
Grade = 5,
Pets = new Pet[] {
new Pet { GivenName = "Fluffy" }
}
}
},
Address = new Address { State = "WA", County = "King", City = "Seattle" },
IsRegistered = true
};
await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, andersonFamily);
client.Dispose();
}
这段代码效果很好。我的代码几乎相同,除了我传递的用于将 JSON 保存到数据库中的类。它总是停在线上
await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + coll.Id, this);
我的整个代码如下
public static async Task Save(int UserId, int productID, string code, string language, string dataOraLettura, string longitudine, string latitudine, string nazione_lettura)
{
CultureInfo ciEN = CultureInfo.GetCultureInfo("en-US");
CodeType ScannedCode = new CodeType
{
Code = code,
ProductId = productID,
ScanLog = new List<CodeType.ScanDataType>()
};
ScannedCode.ScanLog.Add(new CodeType.ScanDataType
{
Location = new Microsoft.Azure.Documents.Spatial.Point(double.Parse(longitudine, ciEN.NumberFormat), double.Parse(latitudine, ciEN.NumberFormat)),
ScanType = CodeType.ScanDataType.eScanType.Alert,
UserId = UserId.ToString(),
TimeStamp = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmssffff"))
});
await ScannedCode.AddAsync();
}
public async Task AddAsync()
{
using (DocumentClient client = new DocumentClient(new Uri(WebConfigurationManager.AppSettings["DbURI"]), WebConfigurationManager.AppSettings["DbKEY"]))
{
var CodeDocuments = client.CreateDocumentQuery<CodeType>("dbs/" + database.Id + "/colls/" + coll.Id).Where(a => a.Code == this.Code).ToArray();
if (CodeDocuments.Length == 0)
await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + coll.Id, this);
}
}
这似乎是异步任务块,它没有将控制权返回给调用方,然后保持循环执行。
正确,您有一个异步阻止另一个异步的经典情况。您应该在等待 ScannedCode.AddAsync() 上将 ConfigureAwait 设置为 false;
await ScannedCode.AddAsync().ConfigureAwait(false);
这使它在线程池线程上恢复,而不是在 ASP.NET 请求上下文上恢复。
您可以阅读以下文章 http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html 其中很好地解释了这一点以及使用异步代码时的其他最佳实践。