简体   繁体   English

GC.Collect()和PerformanceCounter

[英]GC.Collect() and PerformanceCounter

A colleague of mine is convinced there is a memory leak in Oracle's odp.net ado.net implementation. 我的一位同事确信Oracle的odp.net ado.net实现中存在内存泄漏。 He has written a test program to test this theory and is doing the following after calling dispose on each object in order to determine how much memory is being freed: 他编写了一个测试程序来测试该理论,并在对每个对象调用dispose以确定释放了多少内存后执行以下操作:

PerformanceCounter p = new PerformanceCounter("Memory", "Available Bytes");

GC.Collect();
GC.WaitForPendingFinalizers();

float mem = p.NextValue();

The resulting performance value is then compared with a value retrieved prior to disposing of the object. 然后将所得的性能值与在处置对象之前获取的值进行比较。 Will this produce accurate results? 这会产生准确的结果吗?

I think the best way to do this is to use GC.GetTotalMemory(true) . 我认为最好的方法是使用GC.GetTotalMemory(true) You can call it before allocating the object to record how much memory was allocated then. 您可以在分配对象之前调用它,以记录当时分配了多少内存。 Then you create your object, maybe perform some operation on it, dispose it, make sure there are no references to it (probably just setting the local variable to null ) and then call it again. 然后创建对象,也许对其执行一些操作,将其处置,确保没有对其的引用(可能只是将局部变量设置为null ),然后再次调用它。

Keep in might that the returned value might not be completely exact, per the documentation, the method will return: 请记住,根据文档,返回值可能不完全准确,该方法将返回:

A number that is the best available approximation of the number of bytes currently allocated in managed memory. 该数字是托管内存中当前分配的字节数的最佳近似值。

After that, you can compare the two values. 之后,您可以比较两个值。 If you do this repeatedly, you can see whether the object is actually leaking managed memory. 如果重复执行此操作,则可以查看该对象是否实际上正在泄漏托管内存。

Of course, this won't help you if the object leaks unmanaged memory. 当然,如果对象泄漏非托管内存,这将无济于事。

Another option is to use a memory profiler, but that might be an overkill if you know where exactly the memory might leak. 另一个选择是使用内存探查器,但是如果您知道确切的内存可能泄漏的地方,那可能就太过分了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM