我需要明确处理SqlDataAdapter吗? [英] Do I need to explicitly dispose SqlDataAdapter?

查看:147
本文介绍了我需要明确处理SqlDataAdapter吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此主题中,有一个建议是在操作后,

In this thread, there's a suggestion that after the operation, the instance of SqlDataAdapter is disposed of explicitly like so.

String connString = @"your connection string here";
String query = "select * from table";

SqlConnection conn = new SqlConnection(connString);        
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
conn.Close();
da.Dispose();

真的有必要吗?关于GC?

Is it really necessary? What about GC?

推荐答案

强烈建议手动处理IDisposable对象。这里有一个很好的语法快捷方式:

It is highly recommended to Dispose IDisposable objects manually. There is a nice syntax shortcut for this:

using (SqlConnection con = new SqlConnection(connstring))
using (SqlCommand com = new SqlCommand())
using (SqlDataAdapter da = new SqlDataAdapter())
{
   com.Connection = con;
   //etc..
}

这样编译器会确保Dispose在大括号中的代码完成执行后,它将在using中创建的所有对象被调用(它使用try..finally完成此操作)。

This way compiler will make sure Dispose gets called on all objects created within "using" after the code in curly brackets finishes executing (it uses try..finally to do this).

GC不负责调用Dispose对象,它的主要职责是从堆中收集不再引用的对象。一个例外是,如果你的类是Finalizable。在这种情况下,GC将确保您的对象的终结器被首先调用,然后它被收集。你可以在Finalizer中调用Dispose,并且有一个很好的模式叫做Dispose Method: http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx

GC is not responsible for calling Dispose on your objects, it's main responsibility is to collect objects from heap that are no longer referenced. One exception to this is if your class is Finalizable. In this case GC will make sure your object's finalizer gets called first, and then it gets collected. You can call Dispose in your Finalizer and there is a nice pattern for this called "Dispose Method": http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx

但一般规则是(有几个异常):如果你实例化一个实现IDisposable的对象,你有责任调用Dispose。

But the general rule is (with a couple of exceptions): If you're instantiating an object that implements IDisposable, it's your responsibility to call Dispose on it.

这篇关于我需要明确处理SqlDataAdapter吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆