开发者

Is it necessary to free objects in final block of try-catch block?

The question is self explanatory :

Foo objfoo;
try
{
  objfoo = new 开发者_如何学JAVAFoo();
  ..........
  .........
}
catch
{

}
finally
{
  objfoo = null;
} 

Is it necessary to free objects like this ?


Note: Setting a local / field to null is not freeing the value. It is instead removing a reference to the value which may or may not make it elligable for collection during the next GC cyle.

To answer the question, no it is not necessary. The JIT`er will calculate the last time a local is used and will essentially remove the local as one of the object's GC roots at that time. Nulling the local out will not speed up this process.

Raymond Chen did an excellent article on this very subject

  • http://blogs.msdn.com/b/oldnewthing/archive/2010/08/10/10048149.aspx


You dont need to as objFoo will be eligible for garbage collection (as per your code) once you leave the try block. objfoo =null just sets the pointer to null, if any other code had a pointer to the object then it wont be garbage collected


Assigning null to a variable will not delete the object it points to.

You don't need to worry about memory cleanup. C# will do it automatically for you, if you're using .NET.


In C#, usually not, because your objects will be freed by the Garbage Collector. Setting it to null later might even extend its lifetime because (depending how the compiler optimizes your code) it is still referenced at that point.

An exception is if the object implements IDisposable, which should be disposed using its Dispose() method. But you usually wrap those in using-blocks.


No , its not necessary , let the CLR do its job.


Unless the objects are accessing unmanaged resources (files, network shares, database connections ...) there is no need to do this, since they will be marked for garbage collection once they are out of scope.

If they are using resources (the StreamReader class for example) it's necessary to dispose of the objects yourself, but that's best accomplished by using a using statement.


Automatic Garbage Collection means you do not need to free memory resources, i.e. objects created with new.

You may need to free other resources you have allocated, eg locking mutexes and maybe context specific to your own project, for which you have the finally block.


There' typically no need to do this. If your function is about to exit then your object will automatically become eligible for garbage collection.

However, if you've got a really long function or it's going to do some blocking operation after the finally block then by setting the variable to null you make it eligible for garbage collection immediately. This might be a good idea if Foo manages a large amount of data, for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜