Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 从测试代码中使用Sos(转储堆等)?_.net_Memory_Garbage Collection_Memory Leaks - Fatal编程技术网

.net 从测试代码中使用Sos(转储堆等)?

.net 从测试代码中使用Sos(转储堆等)?,.net,memory,garbage-collection,memory-leaks,.net,Memory,Garbage Collection,Memory Leaks,我最近在我的应用程序中发现了一个内存泄漏,我想添加一个测试用例来检查它是否保持这种状态。我想做的是: int numberOfInstancesBeforeFunction = GetNumberOfInstancesInMemory(typeof(MyClass)); PerformFunction(); GC.Collect(); int numberOfInstancesAfterFunction = GetNumberOfInstancesInMemory(typeof(M

我最近在我的应用程序中发现了一个内存泄漏,我想添加一个测试用例来检查它是否保持这种状态。我想做的是:

 int numberOfInstancesBeforeFunction = GetNumberOfInstancesInMemory(typeof(MyClass));

 PerformFunction();

 GC.Collect();

 int numberOfInstancesAfterFunction = GetNumberOfInstancesInMemory(typeof(MyClass));

 Assert.AreEqual(numberOfInstancesBeforeFunction, numberOfInstancesAfterFunction, "mem leak");
这可能吗

谢谢


Euan

在@Adam Robinson的公认答案中,有关于如何实现这一目标的建议

GetNumberOfInstancesInMemory
必须检查
MyClass
object
WeakReference
s的静态容器,以查看有多少返回
thisReference.IsAlive=true
(并删除任何具有
isAlive=false

MyClass
的任何构造都会向静态容器添加对自身的引用

我认为有一种优雅的Linq方法可以封装所需的逻辑


我不知道是否有任何方法可以做到这一点,而不将额外的代码合并到您的
MyClass

@Euan-太好了,但请注意@Hans Passant的警告:在这一过程中,我们将引入新的漏洞。经典的海森堡机会。您是否找到了从代码中实际控制sos的方法?我希望能够做的不仅仅是参考电子计数。。。