Good Day!
I’m using MSTest in VS2010. Why accessors are not garbage collected after test execution? Here is my code. It’s pretty simple.
[TestClass]
public class CheckStringsWorkTest
{
CheckProcess checkProcess = null;
CheckProcess_Accessor checkProcess_Accessor;
[TestMethod]
public void StringShaveTest()
{
// MessageBox.Show("Start snapshot 1");
checkProcess = new CheckProcess();
checkProcess_Accessor = new CheckProcess_Accessor(new PrivateObject(checkProcess));
checkProcess.Dispose();
checkProcess = null;
}
[TestCleanup()]
public void RunAfterAllTests()
{
// If uncomment then GC is OK
//checkProcess_Accessor = null;
try
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
catch { }
// MessageBox.Show("Start snapshot 2");
}
As far as i understand – accessors use PrivateObject as a wrapper to hold actual object. But if I dispose and set object to null (checkProcess), cleared the reference, so the only reference to it is from accessor – why it can’t be collected? It holds actual object, not the copy of it.
You’re not nulling the checkProcess_Accessor field in your class so it, and everything it has a link to is still live and can not be collected.
PrivateObject is obviously keeping a reference to the checkProcess it is being passed, and in turn checkProcess_Accessor must be keeping a reference to the PrivateObject. You could still get access to checkProcess via the accessor and the PrivateObject (although you might need to use reflection to do so if all the references are private) so the object can’t be collected.
It’s a really bad idea to try and force garbage collection by the way, but I’m sure you have a valid reason for doing it.