Today I experienced the following issue:
I had a class where I would open a SqlConnection, do some actions, and then in the deconstructor I closed the SqlConnection.
~Dumper()
{
this._sqlConnection.Close();
}
Unfortunately every time my program ran it stopped with this error:
(click to enlarge)
Well it seems that you cannot close a SqlConnection in a ~Deconstructor block.
So the solution is implementing the IDisposable interface
internal class Dumper : IDisposable { private readonly SqlConnection _sqlConnection; public Dumper() { //build and open the connection this._sqlConnection = new SqlConnection(Settings.Default.ConnectionString); this._sqlConnection.Open(); } /// <summary> /// Some function /// </summary> /// <param name="param">param</param> public void SomeFunction(SomeParameter param) { } public void Dispose() { this._sqlConnection.Close(); } }
And to use it you do this:
using (Dumper dumper = new Dumper()) { dumper.SomeFunction(myParam); }
This will cause dumper to be Disposed after the } and it will no longer be available