From f958f2bf5f6be374719cb1fbdf17131551857dd4 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Thu, 15 Apr 2021 09:57:04 -0400 Subject: [PATCH] Fix closure in HttpConnectionPoolManager.StartMonitoringNetworkChanges (#50487) --- .../HttpConnectionPoolManager.cs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs index b8fafcca13614..cf276ab93bb01 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPoolManager.cs @@ -163,17 +163,20 @@ public void StartMonitoringNetworkChanges() // Monitor network changes to invalidate Alt-Svc headers. // A weak reference is used to avoid NetworkChange.NetworkAddressChanged keeping a non-disposed connection pool alive. - var poolsRef = new WeakReference>(_pools); - NetworkAddressChangedEventHandler networkChangedDelegate = delegate - { - if (poolsRef.TryGetTarget(out ConcurrentDictionary? pools)) + NetworkAddressChangedEventHandler networkChangedDelegate; + { // scope to avoid closure if _networkChangeCleanup != null + var poolsRef = new WeakReference>(_pools); + networkChangedDelegate = delegate { - foreach (HttpConnectionPool pool in pools.Values) + if (poolsRef.TryGetTarget(out ConcurrentDictionary? pools)) { - pool.OnNetworkChanged(); + foreach (HttpConnectionPool pool in pools.Values) + { + pool.OnNetworkChanged(); + } } - } - }; + }; + } var cleanup = new NetworkChangeCleanup(networkChangedDelegate);