Azure Function CosmosDB变更源触发器是否自动释放JsonDocument?
CosmosDB变更源触发器中JsonDocument的释放问题
你的函数代码
[Function("Example")] public async Task Run([CosmosDBTrigger( databaseName: "%DATABASE_NAME%", containerName: "example-container", Connection = "EXAMPLE_DATABASE_CONNECTION", LeaseContainerName = "example-container-leases", LeaseContainerPrefix = "Example", CreateLeaseContainerIfNotExists = true)] IReadOnlyList<JsonDocument> documents) { // do stuff with the documents }
文档说明引用
JsonDocument builds an in-memory view of the data into a pooled buffer. Therefore the JsonDocument type implements IDisposable and needs to be used inside a using block.
问题解答
Azure Functions会自动处理这些JsonDocument的释放吗?
不会。CosmosDB触发器仅负责将变更事件映射为IReadOnlyList<JsonDocument>集合,Azure Functions框架没有内置逻辑自动遍历并释放集合中的每个JsonDocument实例。需要手动释放吗?
需要。你必须手动处理JsonDocument的释放,推荐两种方式:
// 方式1:逐个处理文档时用using块包裹 foreach (var doc in documents) { using (doc) { // 编写当前文档的业务处理逻辑 } } // 方式2:批量释放(适合无需逐个处理的场景) try { // 编写文档集合的整体处理逻辑 } finally { foreach (var doc in documents) { doc?.Dispose(); } }
- 若完全不释放会在函数中引发问题吗?
会引发严重问题。JsonDocument依赖共享内存池存储数据视图,不释放的话,这些池化缓冲区无法被回收复用。随着函数触发次数增多,内存池会被耗尽,后续创建JsonDocument时无法获取可用缓冲区,进而抛出内存相关异常,导致函数执行失败,甚至引发进程崩溃。
内容的提问来源于stack exchange,提问作者FullStackOverflowDev
相关产品推荐
相关产品推荐

