It is possible to call all the methods of the .NET Memory Profiler API even when the program is not running under the profiler. The methods will never throw an exception. If not running under the profiler, then all methods will return immediately without performing any action, and all the memory assertion methods will return true.
The property MemProfiler.IsProfiling can be used to determine whether the program is running under the profiler or not.
There are a few common scenarios when running the profiler API:
1. Calling the API methods from within normal code that will be included in the release build:
void ShowDialog()
{
MemProfiler.FastSnapshot();
// Show the
dialog
MemAssertion.NoNewInstances( ...
);
}
2. Making the calls to the profiler API conditional, i.e., dependent on some compiler-defined symbol:
void ShowDialog()
{
#if ENABLE_MEM_ASSERTIONS
MemProfiler.FastSnapshot();
#endif
// Show
the dialog
#if
ENABLE_MEM_ASSERTIONS
MemAssertion.NoNewInstances( ...
);
#endif
}
3. Only using the API from dedicated test methods that are not included in the release build, or at least will never be called when running the release build.
[Test]
void
TestShowDialog()
{
MemProfiler.FastSnapshot();
ShowDialog();
Assert.IsTrue( MemAssertion.NoNewInstances( ... ) );
}
Each of the scenarios above has advantages and disadvantages.
The first scenario is probably the easiest to implement. The API calls and memory assertions are inserted directly into the code that needs to be tested. If the program is not running under the profiler, the performance impact will be very low (the method calls will return immediately after checking a static boolean field). One disadvantage is that the API methods are actually called, making it necessary to include the (redistributable) files MemProfiler.dll or MemProfiler2.dll when distributing the program.
The second scenario avoids the necessity of distributing the MemProfiler.dll file, but it adds extra code around each profiler API call.
The last scenario separates the profiler API calls from the program, allowing the program to be distributed without MemProfiler.dll and MemProfiler2.dll. If working with a unit-testing framework, this might be the preferred way of using the API. However, it may be more suitable to call some API methods from the real code, e.g., MemProfiler.AddRealTimeComment.