110,565
社区成员
发帖
与我相关
我的任务
分享
Close and Dispose are basically the same thing on an ADO.NET connection object for providers shipped by Microsoft,and topically for 3rd party providers as well(haven't seen one that does it differently,but you never konw:).The only difference is that Dispose alse clears the connection string.Calling only one of them is enough-whichever you prefer or applies more to your scenario(e.g.C# "using" statement calls Dispose).
-
Pablo Castro
Program Manager-ADO.NET Team
Microsoft Corp.
微软ADO.NET Team经理说SqlConnection的Close和Dispose实际是做的同一件事,唯一的区别是Dispose方法会清空ConnectionString,即设置其为null。
SqlConnection conn = new SqlConnection("server=localhost;database=northwind;uid=sa;pwd=sa");
conn.Open();
conn.Close();
conn.Open();
conn.Dispose();
conn.Open();
运行上例发现Close掉的 SqlConnection仍然可以Open,Dispose后的却不可以Open,这是因为调用Dispose之后清空了ConnectionString。如果Dispose后给ConnectionString重新赋值,则不会报错。
Close会将连接归还给连接池,不是归还SqlConnection对象,而是归还SqlConnection.Open()时引用的DbConnectionInternal对象,DbConnectionInternal对象在连接池暂存;而Dispose方法是标记GC可回收的对象,但不是马上回收。
try…catch…finally pattern可以让程序员自订错误异常信息,using block则不行,using block的特性是自动调用Dispose方法,不用手动调用Close方法,性能上基本无差别。
Dispose会执行Close方法。
protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null;
this._poolGroup = null;
this.Close();
}
this.DisposeMe(disposing);
base.Dispose(disposing);
}
using block要求对象必须实现IDisposable接口,因为using block会自动调用Dispose方法。
class MyCls : IDisposable
{
public MyCls()
{ }
public void Dispose()
{
Console.WriteLine("Disposed");
}
}
class Program
{
static void Main(string[] args)
{
//使用using会自动调用Dispose()方法,using语句括号中的类必须实现IDisposable接口。
using (MyCls cls = new MyCls())
{
Console.WriteLine("Quit");
}
MyCls cls1=null;
//等价于
try
{
cls1= new MyCls();
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
finally
{
cls1.Dispose();
}
Console.ReadLine();
}
}