c# - 无法使用 Cosmos 3.3 sdk 使用 CreateItemAsync 写入我的容器
问题描述
我正在使用 Cosmos 3.3 sdk,下面是写入我的容器的代码。
public void WriteErrorLogs(Error entity, string collectionName)
{
try
{
Container container = cosmosclient.GetContainer(databaseName, collectionName);
entity.LogID = Guid.NewGuid().ToString();
container.CreateItemAsync<Error>(entity, new PartitionKey(entity.LogID));
}
catch (Exception ex)
{
throw ex;
}
}
cosmos 中的容器看起来像这样,以分区键为 id
错误类是这样的
public class Error
{
[JsonProperty(PropertyName = "id")]
public string LogID { get; set; }
public System.DateTime DateStamp { get; set; }
public string EID { get; set; }
public string Message { get; set; }
public string StackTrace { get; set; }
public string InnerException { get; set; }
我将分区键定义为 LogID,它是一个 guid。由于代码约束,该方法需要同步。不知道我错在哪里,但在调试时总是得到“容器错误 CS0103:名称 'container' 在当前上下文中不存在”并且没有创建日志。任何帮助都会非常感激,谢谢
解决方案
你正在做一个即发即弃,CreateItemAsync
是一个Task
,一个异步操作,你没有在等待它。
public async Task WriteErrorLogs(Error entity, string collectionName)
{
try
{
Container container = cosmosclient.GetContainer(databaseName, collectionName);
entity.LogID = Guid.NewGuid().ToString();
await container.CreateItemAsync<Error>(entity, new PartitionKey(entity.LogID));
}
catch (Exception ex)
{
throw ex;
}
}
无论您打电话到哪里,您WriteErrorLogs
都需要await
它。
例如:
await WriteErrorLogs(entity, "myerrorcollection")
在您的构建过程中,可能会出现指向此特定问题的警告。
编辑:基于 OP 评论,添加如何强制操作同步,但不建议这样做,您可能会以死锁结束,请参阅https://stackoverflow.com/a/24298425/5641598
public void WriteErrorLogs(Error entity, string collectionName)
{
try
{
Container container = cosmosclient.GetContainer(databaseName, collectionName);
entity.LogID = Guid.NewGuid().ToString();
container.CreateItemAsync<Error>(entity, new PartitionKey(entity.LogID)).GetAwaiter().GetResult();
// or ItemResponse<Error> response = container.CreateItemAsync<Error>(entity, new PartitionKey(entity.LogID)).Result;
// or container.CreateItemAsync<Error>(entity, new PartitionKey(entity.LogID)).Wait();
}
catch (Exception ex)
{
throw ex;
}
}
推荐阅读
- javascript - CSS 和 JavaScript:如何创建受渲染高度或 innerText 长度限制的 DOM 子树?
- angular - ngmodule 模块解析错误,带有意外字符'@'
- python - Numpy:将二维高斯和pdf生成为数组
- python - Python - 匹配excel中2个表中最接近的值
- java - Android - 从 DatePickerDialog 更改线条颜色
- angular - 我的对象数组在本地存储中存储了两次
- java - 无法更改标签和按钮值
- php - PHP 新手,需要忽略函数中的部分变量
- javascript - 如何用中间省略号截断反应元素中溢出的文本?
- flutter - 颤振:垂直中心柱