Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is necessary to dispose DbCommand after use?

Tags:

c#

.net

oracle

We use Enterprise Library 3.0 to access Oracle DB (microsoft oracle client). What happens when I do not dispose a DbCommand instance after a stored procedure or function is called? Does .NET automatically garbage collect them? Note that we do make sure that the transaction/connection gets closed and disposed properly.

like image 467
Vivek Avatar asked Jul 01 '09 18:07

Vivek


2 Answers

This is a duplicate, but I don't have time to find the original.

If it implements IDisposable, and if you created it, then you need to call Dispose on it. That's why the developer of the class made it implement IDisposable.

The garbage collector does not call Dispose on all IDisposable-implementing objects.

like image 189
John Saunders Avatar answered Sep 22 '22 07:09

John Saunders


From the documentation for IDisposable:

The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.

Given this, an object that implements IDisposable potentially maintains references to unmanaged resources. These resources are not released until the garbage collector comes along and collects the object. However, since you cannot know when the garbage collector will do this, disposable objects (such as OracleDbCommand) can hang around far longer than you might want them to.

If an object implements IDisposable, you should call it as soon as possible to release the unmanaged resources that it holds references to. This can be accomplished by either calling Dispose directly or by declaring it within a using block.

like image 20
Mike Hofer Avatar answered Sep 19 '22 07:09

Mike Hofer