Created
August 5, 2017 17:57
-
-
Save Krumelur/cd6166e28fa2f0951035436dca002d0a to your computer and use it in GitHub Desktop.
This file contains 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
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