Skip to content

Commit 8212a95

Browse files
committed
Improved cleanup on .NET Standard 2.0 polyfill
1 parent 9e7f12a commit 8212a95

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Microsoft.Toolkit.Mvvm/Messaging/WeakRefMessenger.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,11 @@ void IMessenger.Cleanup()
271271
{
272272
type2s.Add(enumerator.Key);
273273
}
274+
275+
#if !NETSTANDARD2_1
276+
// Do the cleanup for the list of keys that are weakly tracked too
277+
enumerator.Value.Cleanup();
278+
#endif
274279
}
275280

276281
// Remove all the mappings with no handlers left
@@ -368,6 +373,25 @@ public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
368373
}
369374
}
370375
}
376+
377+
/// <summary>
378+
/// Trims the list of tracked <typeparamref name="TKey"/> instances.
379+
/// </summary>
380+
public void Cleanup()
381+
{
382+
for (LinkedListNode<WeakReference<TKey>>? node = this.keys.First; !(node is null);)
383+
{
384+
LinkedListNode<WeakReference<TKey>>? next = node.Next;
385+
386+
// Remove all the nodes with a target that has been collected
387+
if (!node.Value.TryGetTarget(out _))
388+
{
389+
this.keys.Remove(node);
390+
}
391+
392+
node = next;
393+
}
394+
}
371395
}
372396
#endif
373397

0 commit comments

Comments
 (0)