简体   繁体   English

.NET内存泄漏

[英].NET Memory Leak

I have an ASP.NET application that has multiple helper classes. 我有一个具有多个帮助程序类的ASP.NET应用程序。 I'm a little worried about Memory leaks. 我有点担心内存泄漏。 Each time i want to use a helper class member function i call them like this 每次我想使用助手类成员函数时,都这样调用它们

new SampleHandler().DoFunction();

Since it dosen't have any strong reference to the object created can I guarantee whether GC will clear the memory for the object created ? 由于它对创建的对象没有任何强引用,我可以保证GC是否会清除创建对象的内存吗?
Since there is a high chance for me that I won't be using the object again in the page I started coding like this. 由于我很有可能不再在页面中再次使用该对象,因此我开始像这样进行编码。

Note: There are numerous calls to various member functions belonging to different helper classes in the code behind file performed in the same way . 注意:在文件后面的代码中,以相同的方式执行了对属于不同帮助器类的各种成员函数的大量调用

Yes, since there are no other outstanding references, the instance created by new SampleHandler() will be eligible for collection as soon as DoFunction() returns. 是的,因为没有其他未完成的引用,所以由new SampleHandler()创建的实例将在DoFunction()返回时有资格进行收集。

There is, however, no guarantee about the time when the GC will collect that instance, as usual. 但是,不能像往常一样保证GC收集该实例的时间。

The garbage collector will take care of unused references. 垃圾收集器将处理未使用的引用。 So you don't need to worry about a memory leak. 因此,您无需担心内存泄漏。 But if you create "garbage"-objects very fast you could have temporary memory pressure. 但是,如果您非常快地创建“垃圾”对象,则可能会有暂时的内存压力。

But if you don't need the instance anyway or the instances are exchangeable you should consider to make the method static . 但是如果仍然不需要实例或实例是可交换的,应该考虑使方法static

public class SampleHandler
{
    public static void DoFunction()
    {
        // ...
    }
}

Then you would call it: 然后您将其称为:

SampleHandler.DoFunction();

There is no problem with static methods in ASP.NET even if it's a multithreaded environment. 即使是多线程环境,ASP.NET中的静态方法也没有问题。 But you should be careful with static fields. 但是您应该注意静态字段。

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

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