简体   繁体   中英

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

在C#中, connection.Dispose()是什么意思?

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(); 
 }
}

A class implements IDisposable interface contains a method called Dispose() , where you can release resources or do something else.

Also, a using statement can help to call Dispose() method automatically.

using (SqlConnection connection  = new SqlConnection(connStr))
{
   //do something
}// it will automatically Dispose() here

What happens when you call myClass.Dispose() depends on what you wrote in the Dispose method. For example:

public class MyClass : IDisposable
{
   //since MyClass implements IDisposable, it must contain a Dispose() method otherwise will compile error
   public void Dispose()
   {
      // do something
   }
}

so if you want to know what happened when you call connection.Dispose() , you must take a look at the Dispose() method of the class of connection(maybe it's a SqlConnection?). If it's a .NET built-in library(which means you can't get the source code easily), you can use a tool to help called Reflector

Generally Dispose is called to free resources when you are finished using the component.

The Dispose method on a SqlClientConnection object will force the connection to close.

It is a common pattern that can be found not just in .Net but Java too.

MSDN should provide all the documentation you need on the correct way to call Dispose

the conn.Dispose() is call the function in unmanage code.

in fact when programming,you needn't to call this function,just call the conn.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM