0

I've recently tracked down a memory leak in my application and I'd like to add a test case to check that it stays that way. What I want to do is this:

 int numberOfInstancesBeforeFunction = GetNumberOfInstancesInMemory(typeof(MyClass));

 PerformFunction();

 GC.Collect();

 int numberOfInstancesAfterFunction = GetNumberOfInstancesInMemory(typeof(MyClass));

 Assert.AreEqual(numberOfInstancesBeforeFunction, numberOfInstancesAfterFunction, "mem leak");

Is this possible?

Thanks,

Euan

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
Euan
  • 1
  • Did you ever find a way to actually control sos from code? I'd like to be able to do more than just reference counting... – PeterJCLaw Nov 18 '10 at 19:41

1 Answers1

0

There is advice on how to achieve this using WeakReference in the accepted answer from @Adam Robinson here.

GetNumberOfInstancesInMemory would have to check a static container of MyClass object WeakReferences to see how many return thisReference.IsAlive = true; (and remove any that have isAlive = false.

Any construction of MyClass would add a reference to itself to the static container.

I would think there's an elegant Linq way to encapsulate the required logic.

I don't know if there is any way to do this without incorporating extra code into your MyClass.

Community
  • 1
  • 1
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
  • @Euan - great, but take note of @Hans Passant's caveat re introducing new leaks along the way. Classic Heisenbug opportunity. – Steve Townsend Oct 03 '10 at 15:00