简体   繁体   English

引用静态属性是否会导致内存泄漏

[英]Does references to static properties cause memory leaks

I have a long-running application that consistently fails due to a memory leak. 我有一个长时间运行的应用程序,由于内存泄漏而始终失败。

I suspect my use of static properties may be the cause. 我怀疑我使用静态属性可能是原因。 Here's an example of what I have today: 这是我今天所拥有的示例:

public class StaticReferences
{
    public static readonly object Fixed1 = new object();
}

public class ShortLived
{
    public object Object1;
}

public class Doer // This class is instantiated once
{
    public void DoStuff() // This method is called over and over again.
    {
        var shortLived = new ShortLived() 
        {
            Object1 = StaticReferences.Fixed1
        };
    }
}

Will an instance of ShortLived with its reference to StaticReferences.Fixed1 (via the ShortLived.Object1 property) get properly garbage collected once it is out of scope? 将实例ShortLived ,其参考StaticReferences.Fixed1 (通过ShortLived.Object1属性)得到妥善收集垃圾一旦超出范围?

No, just referencing global static properties won't create a memory leak. 不,仅引用全局静态属性不会造成内存泄漏。 The example you posted is fine. 您发布的示例很好。 shortLived will be cleaned up once its scope is over and the reference to Fixed1 will get cleaned up when your program exits. shortLived将被清理一次,它的范围是在和参考Fixed1将得到清理,当你的程序退出。 Your problem is very likely elsewhere but it's impossible to say from your simple example. 您的问题很可能在其他地方出现,但是无法通过简单的示例来说明。 Do you have any proof that you're looking at a memory leak? 您是否有证据证明您正在查看内存泄漏?

I suggest you use a memory profiler or get a full memory dump and analyze it (WinDbg is free but there are other, easier to use but pay tools, too). 我建议您使用内存分析器或获取完整的内存转储并进行分析(WinDbg是免费的,但还有其他一些更易于使用但需要付费的工具)。 Another tool you can try using is DebugDiag from Microsoft (also free) - get a dump and then run it through DebugDiag to get a memory report. 您可以尝试使用的另一个工具是Microsoft的DebugDiag (也是免费的)-获取转储,然后通过DebugDiag运行它以获取内存报告。

As @EricJ mentioned in his comment, the profiler in Visual Studio 2015 is also a great tool to analyze memory use and it's available in all editions, including the free Community Edition . 正如@EricJ在评论中提到的那样,Visual Studio 2015中的事件探查器也是分析内存使用情况的好工具,并且在所有版本中都可用,包括免费的Community Edition

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

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