From 22ca6daafb03e6e159d91d7cf90da5e847bb1892 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 18 Nov 2021 12:34:41 +0100 Subject: [PATCH] Fix app domain unloading issue on .NET Framework Port of https://github.com/CommunityToolkit/dotnet/commit/e2b336184f51fcd755f3151222ff948176ee954c --- .../Messaging/Internals/System/Gen2GcCallback.cs | 10 ++++++++++ .../Messaging/WeakReferenceMessenger.cs | 1 + 2 files changed, 11 insertions(+) diff --git a/Microsoft.Toolkit.Mvvm/Messaging/Internals/System/Gen2GcCallback.cs b/Microsoft.Toolkit.Mvvm/Messaging/Internals/System/Gen2GcCallback.cs index 115e2ee4fa8..649de08eff9 100644 --- a/Microsoft.Toolkit.Mvvm/Messaging/Internals/System/Gen2GcCallback.cs +++ b/Microsoft.Toolkit.Mvvm/Messaging/Internals/System/Gen2GcCallback.cs @@ -41,6 +41,16 @@ private Gen2GcCallback(Action callback, object target) /// The target object to pass as argument to . public static void Register(Action callback, object target) { +#if NETSTANDARD2_0 + if (RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework")) + { + // On .NET Framework using a GC callback causes issues with app domain unloading, + // so the callback is not registered if that runtime is detected and just ignored. + // Users on .NET Framework will have to manually trim the messenger, if they'd like. + return; + } +#endif + _ = new Gen2GcCallback(callback, target); } diff --git a/Microsoft.Toolkit.Mvvm/Messaging/WeakReferenceMessenger.cs b/Microsoft.Toolkit.Mvvm/Messaging/WeakReferenceMessenger.cs index 28828ef0b8c..231dc9d1870 100644 --- a/Microsoft.Toolkit.Mvvm/Messaging/WeakReferenceMessenger.cs +++ b/Microsoft.Toolkit.Mvvm/Messaging/WeakReferenceMessenger.cs @@ -30,6 +30,7 @@ namespace Microsoft.Toolkit.Mvvm.Messaging /// The type will automatically perform internal trimming when /// full GC collections are invoked, so calling manually is not necessary to /// ensure that on average the internal data structures are as trimmed and compact as possible. + /// Note: this is not supported when running on .NET Framework, due to app domain unloading issues. /// /// public sealed class WeakReferenceMessenger : IMessenger