On 22 Aug 2005 08:53:14 -0700, "jasonkeste r" <ja*********@gm ail.com>
wrote:
As I mentioned below, you are not disposing of your connection when you
are finished with it. If you wrap it in a using block, it will be
marked for garbage collection immediately after you close it.
Jason Kester
Expat Software Consulting Services
http://www.expatsoftware.com/
Not quite so. If your object uses a connection, simply disposing of it
is not the right way to close a connection. Instead, the connection
should be explicitly closed in the Dispose method of the IDisposable
interface:
public class MyWarrer : IDisposable
{
private SqlConnection _conn = null;
private bool _connIsMine = false;
// Constructor
public MyWrapper( SqlConnection conn )
{
if( conn != null )
{
this._conn = conn;
}
else
{
this._conn = new SqlConnection() ;
this._connIsMin e = true;
}
}
...
// IDisposable implementation - clean up
public void Dispose()
{
if( this._connIsMin e
&& this._conn != null )
{
this._conn.Clos e();
this._connIsMin e = false;
}
}
}
Then elsewhere you can use something like this:
using( MyWrapper wrapper = new MyWrapper( null ) )
{
// do you stuff
}
The above code allows you to use multiple wrappers and share the same
connection between them w/o risking leaving it open after the work is
done. The wrapper where the connection is created will be the one who
closes it as well. Normally, this the outermost wrapper in the calling
chain, assuming you are using wrappers from within each other.