首页 > 解决方案 > 无法使用 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' 在当前上下文中不存在”并且没有创建日志。任何帮助都会非常感激,谢谢

标签: c#azure-cosmosdbazure-cosmosdb-sqlapi

解决方案


你正在做一个即发即弃,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;
    }

}

推荐阅读