Memory Assertions Session

Each time a memory assertion is performed, a full garbage collection is performed. This garbage collection has to be performed in order to make sure that all instances that are eligible for garbage collection have really been collected. If more than one assertion is to be performed at the same time, the BeginAssertions and EndAssertions methods should be used to avoid excessive garbage collections. The garbage collection is performed when calling BeginAssertions, and then no more garbage collections are performed for memory assertions until EndAssertions is called.

It is also recommended to call BeginAssertions/EndAssertions to avoid falsely identifying instances as memory leaks. This is especially important if using the NoNewInstancesExcept methods. Consider the following assertion:

MemProfiler.FastSnapshot();

 

// Do some operation that will be checked

 

MemAssertion.NoNewInstancesExcept( new Type[] { typeof( SomeClass), typeof( SomeOtherClass ) );

The problem with the assertion above is that at the time of the assertion call, a new Type array exists, and the assertion will fail. If BeginAssertions/EndAssertions is used, this will be avoided, since instances created in-between BeginAssertions and EndAssertions are ignored by the memory assertion.

MemProfiler.FastSnapshot();

 

// Do some operation that will be checked

 

BeginAssertions();

MemAssertion.NoNewInstancesExcept( new Type[] { typeof( SomeClass), typeof( SomeOtherClass ) );

EndAssertions();

NOTE! The BeginAssertions method returns an IDisposable object. Disposing this object is equivalent to calling EndAssertions, making it possible to use the using pattern:

using( MemAssertion.BeginAssertions() )

{

   MemAssertion.NoNewInstances( ... );

   MemAssertion.NoInstances( ... );

}

If using is not used, it is recommended to call EndAssertions in a finally block, to avoid having unmatched BeginAssertions/EndAssertions pairs.