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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With