user1867045
user1867045

Reputation: 85

How to test if an object is disposed and GC'ed?

I'm writing some code to delete an object and wanted to have a unit test to ensure that the object is always deleted. What is the best way to do this? If GC is to work you should not be holding any references so how can you test without a reference?

Upvotes: 3

Views: 3446

Answers (1)

artelk
artelk

Reputation: 341

There is no way to test if object is disposed in general case.

WeakReference is probably the thing you are looking for. You can create a WeakReference as part of the test and after your code has run this:

WeakReference wr = new WeakReference(obj);
GC.Collect();
Assert.IsTrue(!wr.IsAlive);

Upvotes: 9

Related Questions