无法使用 Cosmos 3.3 sdk 使用 CreateItemAsync 写入我的容器

Unable to write to my container using CreateItemAsync using Cosmos 3.3 sdk

我正在使用 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

错误class是这样的

  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.The 方法需要同步。 不确定我哪里错了,但在调试时总是出现“容器错误 CS0103:名称 'container' 在当前上下文中不存在”并且日志没有得到 created.Any 帮助真的很感激,谢谢

您正在进行即发即弃,CreateItemAsyncTaskasync operation,您没有等待它。

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")

在您的构建过程中,可能 Warnings 指出了这个特定问题。

编辑:根据 OP 评论,添加如何强制操作同步,但不推荐,您可能会以死锁结束,请参阅

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;
    }

}

我发现 issue.It 是一个线程问题,正如 Matias.I 明确指出的 运行 任务作为 Task.Run (async..functioncall).wait() 然后在函数调用中将 createItemasync 定义为同步调用。