You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure Cosmos DB中使用.NET SDK v3的CreateItemStreamAsync()测量消耗的RU?

在Azure Cosmos DB .NET SDK v3中通过CreateItemStreamAsync()测量RU消耗的方法

CreateItemStreamAsync()确实不会像非流式方法那样直接返回RequestCharge属性,但你可以通过以下两种方式获取本次操作的RU消耗:

  • 从ResponseMessage的响应头提取
    该方法返回的ResponseMessage对象包含完整的响应头,其中x-ms-request-charge字段就是操作消耗的RU值。你可以通过头信息直接读取并转换为数值类型:

    using (var itemStream = new MemoryStream(Encoding.UTF8.GetBytes(你的JSON内容)))
    {
        var response = await cosmosContainer.CreateItemStreamAsync(
            itemStream, 
            new PartitionKey("你的分区键值")
        );
    
        if (response.IsSuccessStatusCode)
        {
            if (response.Headers.TryGetValue("x-ms-request-charge", out string ruStr) 
                && double.TryParse(ruStr, out double ruConsumed))
            {
                // 这里拿到了消耗的RU
                Console.WriteLine($"本次操作消耗RU: {ruConsumed}");
            }
        }
    }
    
  • 通过CosmosDiagnostics获取
    ResponseMessage的Diagnostics属性包含请求的详细诊断数据,其中也封装了RequestCharge,你可以直接调用内置方法获取:

    var response = await cosmosContainer.CreateItemStreamAsync(/* 参数略 */);
    if (response.IsSuccessStatusCode)
    {
        var totalRu = response.Diagnostics.GetTotalRequestCharge();
        Console.WriteLine($"本次操作消耗RU: {totalRu}");
    }
    

这两种方式都是SDK原生支持的,不需要额外依赖,能准确获取流式创建操作的RU消耗。

内容的提问来源于stack exchange,提问作者Tanuki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 09:42:32