How IDisposable works in .NET?

IDisposable

                MSDN Says – Provides a mechanism for releasing unmanaged resources .

                 IDisposable doesn’t only apply when you are using a come DLL. If you create an instance of a class which Implement IDisposable then you should actively manage the life time of that object.
Here is the class which implement IDisposable
1

 

 

 

 

If I want to use the instance of this class temporarily, I should declare it in using block like below

2

 

 

 

 

Using is a C# construct that the compiler actually renders as a try finally block calling dispose on the object in the finally. So the using code is functionally prevalent to creating the object using it and calling dispose. Depending on the situation that may mean the resources take longer to clean up as they wait for the next Garbage Collection event or object may retain references to those resources. So the object may never be released and so you app exits or throws OutOfMemory exception.

Using and Disposing SqlConnection

class Program
{
static void Main(string[] args)
{
using (var databaseState = new DatabaseState())
{
string date = databaseState.GetCurrentDate();
Console.WriteLine(date);
}
Console.ReadKey();
}
}
public class DatabaseState:IDisposable
{
private SqlConnection _connection;
public string GetCurrentDate()
{
if(_connection==null)
{
_connection =
new SqlConnection(@"Data Source=JAMEELM\SQL2012DEV;Initial Catalog= SampleDb;Integrated Security=True");
_connection.Open();
}
using (SqlCommand command=_connection.CreateCommand())
{
command.CommandText = "Select getdate()";
return command.ExecuteScalar().ToString();
}
}
public void Dispose()
{
Console.WriteLine("Disposing SqlConnection :{0}", _connection.GetHashCode());
_connection.Close();
_connection.Dispose();
}
}

When we run this program we get the output as date from the server also I have wrote a line of code which displays the hashcode of SqlConnection object. The hashcode will be different, each time we run the program because each time it will create a new SqlConnection object.

3

 

 

Again I am going to run this program by changing the code littile bit by adding the using statements inside a loop

for (int i = 0; i < 1000; i++)
{
using (var databaseState = new DatabaseState())
{
string date = databaseState.GetCurrentDate();
Console.WriteLine(date);
}
}

Every time the using block run, it will create a new SqlConnection and Dispose it.

4

 

 

 

 

 

 

 

 

 
Not Disposing SqlConnection
Change the previous code little bit by removing the using statement

for (int i = 0; i< 1000; i++)
{
var databaseState = new DatabaseState();
string date = databaseState.GetCurrentDate();
Console.WriteLine(date);
}

When we run the program we will get an unhandled exception after creating some SqlConnection objects

5

 

 

 

 

The exception is a time out from trying to connect SqlServer because all the connection in the connection pool are already being used. Inside the loop it creates connection but never dispose it. It will happen whether are no free connection in the pool and we get the error.

We can also specify the Max pool size and connection timeout in Sql connection string arbitrarily

_connection =
new SqlConnection(
@"Data Source=JAMEELM\SQL2012DEV;Initial Catalog=SampleDb;Integrated Security=True;App=Sample;Max pool size=215;Connection Timeout=2");

Enjoy Programming..