Recently, I fixed a leak where an event held an instance alive. It took only a few weeks and I had to fix a leak for the same object again, because someone added another event which caused a leak.
I was now thinking of adding some automatic tests. This test should create the object, destroy the object and validate that the object is not in memory any more.
I guess it's not possible to write some code like:
Initialize();
var object = CreateObject();
Type type = object.GetType();
DestroyObject(object);
// There are a few objects that intentionally keep my object still alive
// up to a certain time.
DestroyFurtherObjectsWithReferenceToMyObject();
GC.Collect();
Assert.IsNull(FindInstanceOf(type));
I think the problem is the FindInstanceOf-method. The GC class, afaik, does not provide a method like that.
Another approach would be creating the object very often, destroying it each time, and then comparing total memory.
I feel this approach is less reliable. In my case, I have to pull up many parts of the application first (thus Initialize
above). After creating and destroying the object, I need to destroy some further objects holding a reference.
If changes are made to those other objects, this could have some bad effects on my test. Don't want to go too much into detail here, but it's not unlikely that my test may eventually fail for random reasons.
So, what would be a possible solution to find out if a certain object stays in memory?