views:

26

answers:

1

Hi, 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

A: 

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.

Steve Townsend
Ah, this works well. Thanks a lot.
Euan
@Euan - great, but take note of @Hans Passant's caveat re introducing new leaks along the way. Classic Heisenbug opportunity.
Steve Townsend