我正在为我的托管应用程序编写验收测试,以确保它在加载和卸载数据时不会泄漏内存。这是我正在做的示例代码:
System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
long memoryBefore = process.PrivateMemorySize64;
// Keep creating new projects.
for (int i = 0; i < 100; i++){
MyApplication.CreateObject();
MyApplication.UnlaodLastCreatedObject();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.GC.WaitForFullGCComplete();
}
为了测试我的进程是否具有相同的内存消耗 (+1MB),我执行以下操作:
// Refresh the memory statistics
process.Refresh();
Assert.Less((decimal)process.PrivateMemorySize64,(decimal)(memoryBefore + (1024 * 1024)));
该测试似乎根本不可靠,因为它不时随机失败。我上面的代码有什么问题吗?是否有不同的方法来测试我的进程是否没有泄漏内存?
编辑 失败是随机的,下面是我的构建服务器输出的屏幕截图,您可以清楚地看到测试不时失败。
谢谢你。