Skip to content

Instantly share code, notes, and snippets.

@Krumelur
Created August 5, 2017 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Krumelur/8c39e49f1a51e4a6504d6eec0a823e21 to your computer and use it in GitHub Desktop.
Save Krumelur/8c39e49f1a51e4a6504d6eec0a823e21 to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.CompilerServices;
namespace LeakTest
{
public class MemoryLeakCheck<T> where T : class
{
string filename;
int lineNumber;
WeakReference<T> reference;
public MemoryLeakCheck(T theObject, [CallerFilePath] string filename = "",
[CallerLineNumber] int lineNumber = 0)
{
this.reference = new WeakReference<T>(theObject);
this.filename = filename;
this.lineNumber = lineNumber;
}
public bool Check()
{
GC.Collect();
GC.WaitForPendingFinalizers();
T theObject = null;
reference.TryGetTarget(out theObject);
bool isAlive = theObject != null;
if (isAlive)
{
Console.WriteLine($"Object allocated at {filename}-{lineNumber} is still alive.");
}
return isAlive;
}
}
class Foo
{
public Foo(string name)
{
_name = name;
}
string _name;
public override string ToString() => "Foo " + _name;
~Foo()
{
Console.WriteLine("Foo " + _name + " is being finalized");
}
}
class Bar
{
public Bar(Foo foo)
{
TheFoo = foo;
}
public Foo TheFoo { get; set; }
public void BarIt()
{
Console.WriteLine("That's my foo: " + TheFoo);
TheFoo = null;
Console.WriteLine("Verifying that Foo is null: " + (TheFoo == null));
}
}
class MainClass
{
public static void Main(string[] args)
{
var o1 = new Bar(new Foo("1"));
var o2 = new Bar(new Foo("2"));
var wr1 = new MemoryLeakCheck<Foo>(o1.TheFoo);
var wr2 = new MemoryLeakCheck<Foo>(o2.TheFoo);
o1.BarIt();
o1 = null;
Console.WriteLine($"o1: {wr1.Check()}");
Console.WriteLine($"o2: {wr2.Check()}");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment