From 462b080bffd202b83b50b22dfd90e1b2f25ff07f Mon Sep 17 00:00:00 2001 From: Timofey Burak Date: Mon, 17 Oct 2022 13:41:23 +0200 Subject: [PATCH] Conditional Assert to warn about compiler-generated targets --- Softeq.XToolkit.Common/Weak/WeakDelegate.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Softeq.XToolkit.Common/Weak/WeakDelegate.cs b/Softeq.XToolkit.Common/Weak/WeakDelegate.cs index a52b890c3..90c0771cb 100644 --- a/Softeq.XToolkit.Common/Weak/WeakDelegate.cs +++ b/Softeq.XToolkit.Common/Weak/WeakDelegate.cs @@ -2,7 +2,9 @@ // http://www.softeq.com using System; +using System.Diagnostics; using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; namespace Softeq.XToolkit.Common.Weak @@ -27,6 +29,7 @@ protected WeakDelegate(object? target, TDelegate @delegate) return; } + AssertCompilerGeneratedTarget(@delegate); DelegateTargetReference = new WeakReference(@delegate.Target); if (!ReferenceEquals(@delegate.Target, target)) { @@ -137,5 +140,18 @@ protected T TryExecuteWeakDelegate(params object?[] parameters) ? DelegateTargetReference?.Target : null; } + + [Conditional("DEBUG")] + private static void AssertCompilerGeneratedTarget(TDelegate @delegate) + { + var isCompilerGenerated = @delegate.Target.GetType().GetCustomAttribute() != null; + if (!isCompilerGenerated) + { + return; + } + + Debug.WriteLine("WeakDelegate's target is compiler-generated, it might be garbage-collected"); + Debug.WriteLine(Environment.StackTrace); + } } }