Skip to content

Commit 030bcc3

Browse files
committed
Minor code improvements to GC callback setup
1 parent ce2d8e9 commit 030bcc3

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

Microsoft.Toolkit.Mvvm/Messaging/WeakReferenceMessenger.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,13 @@ public sealed class WeakReferenceMessenger : IMessenger
6161
/// </summary>
6262
public WeakReferenceMessenger()
6363
{
64+
// Proxy function for the GC callback. This needs to be static and to take the target instance as
65+
// an input parameter in order to avoid rooting it from the Gen2GcCallback object invoking it.
66+
static void Gen2GcCallbackProxy(object target)
67+
{
68+
((WeakReferenceMessenger)target).CleanupWithNonBlockingLock();
69+
}
70+
6471
// Register an automatic GC callback to trigger a non-blocking cleanup. This will ensure that the
6572
// current messenger instance is trimmed and without leftover recipient maps that are no longer used.
6673
// This is necessary (as in, some form of cleanup, either explicit or automatic like in this case)
@@ -69,7 +76,7 @@ public WeakReferenceMessenger()
6976
// mapping to each conditional table for a pair of message and token types) to potentially remain in the
7077
// root mapping structure but without any remaining recipients actually registered there, which just
7178
// adds unnecessary overhead when trying to enumerate recipients during broadcasting operations later on.
72-
Gen2GcCallback.Register(static obj => ((WeakReferenceMessenger)obj).CleanupWithNonBlockingLock(), this);
79+
Gen2GcCallback.Register(Gen2GcCallbackProxy, this);
7380
}
7481

7582
/// <summary>

0 commit comments

Comments
 (0)