简体   繁体   中英

.NET Memory Leak

I have an ASP.NET application that has multiple helper classes. 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 ?
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.

There is, however, no guarantee about the time when the GC will collect that instance, as usual.

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 .

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. But you should be careful with static fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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