栏目导航
热点推荐
- 如何配置Web.config文件 for ASP
- .NET小常识——答你所问
- ASP.NET程序中常用的三十三种代
- 一个“简单”的ASP.NET的服务器
- ASP.NET中使用AJAX中的方式
- 从N层到.NET详细剖析原理(2)
- 十项必须学习的.NET技术
- Visual Basic中文本框处理技巧集
- 几十个ASP.NET性能优化的常用方
- ASP.NET技术FAQ
- Asp.Net细节性问题精萃
- 十天学会ASP.net之第一天
阅览排行
.NET,你忘记了么?(二)——使用using清理非托管资源
www.jz123.cn 2010-10-03 来源: 中国建站 责任编辑(袁袁) 我要投递新闻
有了上述的原因,我们现在只来看使用IDispose接口的类。
在.NET中,绝大多数的类都是运行在托管的环境下,所以都由GC来负责回收,那么我们就不需要实现IDispose接口,而是由GC来自动负责。可是有一些类使用的是非托管资源,那么这个时候,我们就应该去实现IDispose接口,说个比较常用的SqlConnection之类。
写段常用的连接SQL语句的模型:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Study1ConnectionString1"].ConnectionString;
SqlConnection thisConnection = new SqlConnection(connectionString);
thisConnection.Open();
SqlCommand thisCommand = new SqlCommand();
thisCommand.Connection = thisConnection;
thisCommand.CommandText = "select * from [User]";
thisCommand.ExecuteNonQuery();
thisConnection.Close();
其实,作为非托管资源,为了防止我们忘记调用Close,一般都实现了Finalize,因此,即使我们没有Close掉,也会由终结器将这块内存回收。但是,就增加了这块垃圾的代数。
假设说我们写了这样的代码:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Study1ConnectionString1"].ConnectionString;
SqlConnection thisConnection = new SqlConnection(connectionString);
thisConnection.Open();
SqlCommand thisCommand = new SqlCommand();
thisCommand.Connection = thisConnection;
thisCommand.CommandText = "select * form [User]"; //SQL语句错误
thisCommand.ExecuteNonQuery();
thisConnection.Close();
这样的话,我们打开的SqlConnection就没有关闭,只能等待Finalize去关闭了。
这是非常不好的做法。于是,我们可以想到异常处理:
SqlConnection thisConnection = null;
try
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Study1ConnectionString1"].ConnectionString;
thisConnection = new SqlConnection(connectionString);
thisConnection.Open();
SqlCommand thisCommand = new SqlCommand();
thisCommand.Connection = thisConnection;
thisCommand.CommandText = "select * form [User]";
thisCommand.ExecuteNonQuery();
}
finally
{
if (thisConnection != null)
{
thisConnection.Close();
}
}
这样做就不错了,但是代码看起来有些丑陋,可是使用using就让代码优雅了很多,这也是C#比JAVA棒很多的地方,呵呵!
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Study1ConnectionString1"].ConnectionString;
using (SqlConnection thisConnection = new SqlConnection())
{
thisConnection.Open();
SqlCommand thisCommand = new SqlCommand();
thisCommand.Connection = thisConnection;
thisCommand.CommandText = "select * form [User]";
thisCommand.ExecuteNonQuery();
}
上一篇:.NET,你忘记了么(一)—— 遵从CLS 下一篇:.NET,你忘记了么?(三)——关于Array和List的使用