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

后端 未结 4 2042
粉色の甜心
粉色の甜心 2021-01-12 10:09

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

相关标签:
4条回答
  • 2021-01-12 10:20

    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(); 
     }
    }
    
    0 讨论(0)
  • 2021-01-12 10:29

    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

    0 讨论(0)
  • 2021-01-12 10:32

    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

    0 讨论(0)
  • 2021-01-12 10:35

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

    0 讨论(0)
提交回复
热议问题