Created
November 29, 2024 12:29
-
-
Save pictos/4c028ee3d181709d71cbe7a848000b50 to your computer and use it in GitHub Desktop.
Helper Class used to identify memory leaks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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