dotMemory Unit 3.0 Help

Checking for Objects

Checking for objects of a specific type

Checking for objects of a specific type is the main way of finding memory leaks in your code.

[Test] public void TestMethod1() { var foo = new Foo(); foo.Bar(); // 1 dotMemory.Check(memory => //2 Assert.That(memory.GetObjects(where => where.Type.Is<Goo>()).ObjectsCount, Is.EqualTo(0))); // 3 GC.KeepAlive(foo); // prevent objects from GC if this is implied by test logic }
  1. A lambda is passed to the Check method of the static dotMemory type. What this method does is takes a dump of the managed heap. This method will be called only in case you run the test using Run test under dotMemory Unit.
  2. The memory object of the Memory type passed to the lambda contains all memory data for the current execution point.
  3. The GetObjects method returns a set of objects that match the condition passed in another lambda. E.g., what this line does is slices the memory by leaving only objects of the Goo type. The NUnit Assert expression asserts that there should be 0 objects of the Foo type.

Selecting objects by a number of conditions

To slice data by a number of conditions, you can build chains of GetObjects calls. The ObjectSet type has two properties that you can use in test assertions:ObjectsCount and SizeInBytes.

Assert.That(memory.GetObjects(where => where.Type.Is<Foo>()) .GetObjects(where => where.Generation.Is(Generation.LOH).ObjectsCount, Is.EqualTo(0));

dotMemory Unit also provides alternative syntax for object set queries. You can use the ==, &, and | logic operators to combine a number of queries. For example:

Assert.That(memory.GetObjects(where => where.Type == typeof(Foo) & where.Generation == Generation.LOH) .ObjectsCount, Is.EqualTo(0));

Note that open generic types and interfaces are also supported. For example:

public interface IGenericInterface<T1, T2> { } ... dotMemory.Check(memory => Assert.That(memory.GetObjects(where => where.Interface.Is(typeof(IGenericInterface<,>)).ObjectsCount, Is.EqualTo(0)));
Last modified: 16 January 2018