Skip to content

Commit

Permalink
Merge pull request #495 from Softeq/feature/weak-lambda-warning
Browse files Browse the repository at this point in the history
  • Loading branch information
wcoder authored Oct 27, 2022
2 parents 28b2e59 + 462b080 commit d594506
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Softeq.XToolkit.Common/Weak/WeakDelegate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -27,6 +29,7 @@ protected WeakDelegate(object? target, TDelegate @delegate)
return;
}

AssertCompilerGeneratedTarget(@delegate);
DelegateTargetReference = new WeakReference(@delegate.Target);
if (!ReferenceEquals(@delegate.Target, target))
{
Expand Down Expand Up @@ -137,5 +140,18 @@ protected T TryExecuteWeakDelegate<T>(params object?[] parameters)
? DelegateTargetReference?.Target
: null;
}

[Conditional("DEBUG")]
private static void AssertCompilerGeneratedTarget(TDelegate @delegate)
{
var isCompilerGenerated = @delegate.Target.GetType().GetCustomAttribute<CompilerGeneratedAttribute>() != null;
if (!isCompilerGenerated)
{
return;
}

Debug.WriteLine("WeakDelegate's target is compiler-generated, it might be garbage-collected");
Debug.WriteLine(Environment.StackTrace);
}
}
}

0 comments on commit d594506

Please sign in to comment.