Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meant by connection.Dispose() in C#?

Tags:

c#

What is meant by connection.Dispose() in C#?

like image 842
selvaraj Avatar asked Sep 15 '10 06:09

selvaraj


People also ask

What is connection Dispose?

Connection. Dispose() will clean up completely, removing all unmanaged resources preventing that Connection from being used again. Once disposed is called you shouldn't try to use the object any more. Within Dispose(), Close()` will all most certainly be called too.

What is Dispose () in C#?

In the context of C#, dispose is an object method invoked to execute code required for memory cleanup and release and reset unmanaged resources, such as file handles and database connections.

What does Dispose method to with connection object?

Deletes it from the memory.

Does Dispose close connection?

Connections are automatically pooled, and calling Dispose / Close on the connection does not physically close the connection (under normal circumstances).


1 Answers

Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing.

Example:-

void DataTest()
{
 using(SqlConnection conn1 = new SqlConnection(...)) {
  conn1.Open();
  SqlCommand mycommand = new SqlCommand("Select * From someTable", conn1);
  using(SqlDataReader myreader = mycommand.ExecuteReader()) {
   if(myreader != null)
    while(myreader.Read())
     Console.WriteLine(myreader.GetValue(0).ToString() + ":" + myreader.GetTypeName(0));

  }
  mycommand.Dispose(); 
 }
}
like image 126
PrateekSaluja Avatar answered Dec 01 '22 12:12

PrateekSaluja