diff --git a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/KestrelEventSource.cs b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/KestrelEventSource.cs index a5171179db92..d542bd2b285c 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/KestrelEventSource.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/KestrelEventSource.cs @@ -8,7 +8,6 @@ using System.Runtime.CompilerServices; using System.Text; using System.Text.Json; -using System.Threading; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; @@ -39,7 +38,7 @@ internal sealed class KestrelEventSource : EventSource private long _httpRequestQueueLength; private long _currentUpgradedHttpRequests; - private readonly List _options = new(); + private readonly List> _options = new(); private KestrelEventSource() { @@ -224,7 +223,7 @@ public void TlsHandshakeFailed(string connectionId) public void Configuration(int instanceId, string configuration) { // If the event source is already enabled, dump configuration - WriteEvent(11, instanceId, configuration); + WriteEvent(11, instanceId, configuration); } [NonEvent] @@ -252,7 +251,7 @@ public void AddServerOptions(KestrelServerOptions options) { lock (_options) { - _options.Add(options); + _options.Add(new(options)); } Configuration(options); @@ -263,7 +262,14 @@ public void RemoveServerOptions(KestrelServerOptions options) { lock (_options) { - _options.Remove(options); + for (var i = _options.Count - 1; i >= 0; i--) + { + var weakReference = _options[i]; + if (!weakReference.TryGetTarget(out var target) || ReferenceEquals(target, options)) + { + _options.RemoveAt(i); + } + } } } @@ -353,9 +359,18 @@ protected override void OnEventCommand(EventCommandEventArgs command) // Log the options here lock (_options) { - foreach (var option in _options) + for (var i = _options.Count - 1; i >= 0; i--) { - Configuration(option); + var weakReference = _options[i]; + if (!weakReference.TryGetTarget(out var target)) + { + // Remove any options that have been collected + _options.RemoveAt(i); + } + else + { + Configuration(target); + } } } }