From c041512d2a14951cd141721831fef8a0318837ac Mon Sep 17 00:00:00 2001 From: wificlub Date: Thu, 12 Feb 2026 11:03:37 +0800 Subject: [PATCH] Optimize transaction cleanup to prevent memory leaks Enhanced the setter of the Transaction property in CapPublisher: when the property is assigned a null value, _asyncLocal.Value is cleared to avoid memory leaks caused by ExecutionContext holding a reference to CapTransactionHolder. Additionally, Transaction = null was added to the finally block of the method to ensure timely release of transactions. --- src/DotNetCore.CAP/Internal/ICapPublisher.Default.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/DotNetCore.CAP/Internal/ICapPublisher.Default.cs b/src/DotNetCore.CAP/Internal/ICapPublisher.Default.cs index 5ab81266..fed85e85 100644 --- a/src/DotNetCore.CAP/Internal/ICapPublisher.Default.cs +++ b/src/DotNetCore.CAP/Internal/ICapPublisher.Default.cs @@ -46,6 +46,12 @@ public ICapTransaction? Transaction get => _asyncLocal.Value?.Transaction; set { + if (value == null) + { + // Clear the CapTransactionHolder held in the ExecutionContext to avoid long-term reference retention. + _asyncLocal.Value = null; + return; + } _asyncLocal.Value ??= new CapTransactionHolder(); _asyncLocal.Value.Transaction = value; } @@ -184,6 +190,11 @@ private async Task PublishInternalAsync(string name, T? value, IDictionary