Skip to content

Instantly share code, notes, and snippets.

@pictos
Created November 29, 2024 12:29
Show Gist options
  • Save pictos/4c028ee3d181709d71cbe7a848000b50 to your computer and use it in GitHub Desktop.
Save pictos/4c028ee3d181709d71cbe7a848000b50 to your computer and use it in GitHub Desktop.
Helper Class used to identify memory leaks
namespace MemoryLeakTest;
static class MemoryTest
{
static readonly List<WeakReference<object>> weakReferences = [];
public static int Count => weakReferences.Count;
public static void Add(object obj)
{
weakReferences.Add(new(obj));
}
public static async Task IsAliveAsync()
{
RunGC();
for (var i = 0; i < weakReferences.Count; i++)
{
var item = weakReferences[i];
if (item.TryGetTarget(out var target))
{
var type = target.GetType();
var name = type.FullName;
await App.Current!.MainPage!.DisplayAlert("Memory leak!", $"The {name} object of {type} Type is still alive", "Ok");
}
else
{
weakReferences.Remove(item);
}
RunGC();
}
}
static void RunGC()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment