Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to release memory by set obj to null in c#? [duplicate]

Tags:

c#

memory

asp.net

Possible Duplicate:
Setting Objects to Null/Nothing after use in .NET
Do you need to dispose of objects and set them to null?

For large, or high traffic website:

First question:

Will set Object=null (not Disposable ) release memory? Or is other way to release memory?

Second question:

Is explicitly release memory as above necessary in normal code?

like image 591
Eric Yin Avatar asked Dec 16 '22 04:12

Eric Yin


1 Answers

No, it won't do it immediately, and no, it's usually unnecessary if you're writing your code the right way.

If you have a resource that implements IDisposable, call Dispose() on it, or even better, put it in a using(...) block - it's much faster and will release the proper resources. If you have several large objects in the same scope that aren't COM objects or don't implement some form of disposal mechanism, doing:

someObject = null;
GC.Collect();

might help, but you're probably better off restructuring your code so you don't end up in that situation.

If you're doing this before objects go out of scope, it's completely superfluous and makes things worse. More so if you set things to null in your finalizer. For example, never do this:

public void aFunction() {
    SomeThing anObject = new SomeThing();
    // ...
    anObject = null;
}

nor this:

public ~MyClass() {
    this.Something = null; // WRONG!
    this.SomethingElse.Dispose(); // DANGEROUS!
    this.SomeObject.Notify("I got finalized!"); // ALSO DANGEROUS!
}

And, for the sake of completeness, you do this:

Marshal.ReleaseComObject(someObj);

to release a COM object.

like image 103
Ry- Avatar answered May 12 '23 06:05

Ry-