Skip to content

Commit d941575

Browse files
authored
Use a weak reference list to store server options (#35098)
1 parent 52361a3 commit d941575

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

src/Servers/Kestrel/Core/src/Internal/Infrastructure/KestrelEventSource.cs

+22-7
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
using System.Runtime.CompilerServices;
99
using System.Text;
1010
using System.Text.Json;
11-
using System.Threading;
1211
using Microsoft.AspNetCore.Connections;
1312
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
1413

@@ -39,7 +38,7 @@ internal sealed class KestrelEventSource : EventSource
3938
private long _httpRequestQueueLength;
4039
private long _currentUpgradedHttpRequests;
4140

42-
private readonly List<KestrelServerOptions> _options = new();
41+
private readonly List<WeakReference<KestrelServerOptions>> _options = new();
4342

4443
private KestrelEventSource()
4544
{
@@ -224,7 +223,7 @@ public void TlsHandshakeFailed(string connectionId)
224223
public void Configuration(int instanceId, string configuration)
225224
{
226225
// If the event source is already enabled, dump configuration
227-
WriteEvent(11, instanceId, configuration);
226+
WriteEvent(11, instanceId, configuration);
228227
}
229228

230229
[NonEvent]
@@ -252,7 +251,7 @@ public void AddServerOptions(KestrelServerOptions options)
252251
{
253252
lock (_options)
254253
{
255-
_options.Add(options);
254+
_options.Add(new(options));
256255
}
257256

258257
Configuration(options);
@@ -263,7 +262,14 @@ public void RemoveServerOptions(KestrelServerOptions options)
263262
{
264263
lock (_options)
265264
{
266-
_options.Remove(options);
265+
for (var i = _options.Count - 1; i >= 0; i--)
266+
{
267+
var weakReference = _options[i];
268+
if (!weakReference.TryGetTarget(out var target) || ReferenceEquals(target, options))
269+
{
270+
_options.RemoveAt(i);
271+
}
272+
}
267273
}
268274
}
269275

@@ -353,9 +359,18 @@ protected override void OnEventCommand(EventCommandEventArgs command)
353359
// Log the options here
354360
lock (_options)
355361
{
356-
foreach (var option in _options)
362+
for (var i = _options.Count - 1; i >= 0; i--)
357363
{
358-
Configuration(option);
364+
var weakReference = _options[i];
365+
if (!weakReference.TryGetTarget(out var target))
366+
{
367+
// Remove any options that have been collected
368+
_options.RemoveAt(i);
369+
}
370+
else
371+
{
372+
Configuration(target);
373+
}
359374
}
360375
}
361376
}

0 commit comments

Comments
 (0)