Gur*_*epS 3 c# dispose using-statement
我有以下代码:
using (SqlCommand command = new SqlCommand())
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Connection = new SqlConnection();
command.CommandText = "";
command.Parameters.Add(new SqlParameter("@ExperienceLevel", 3).Direction = System.Data.ParameterDirection.Input);
SqlDataReader dataReader = command.ExecuteReader();
}
Run Code Online (Sandbox Code Playgroud)
在声明SqlConnection的地方是否有任何功能影响我目前正在声明它而不是这样?:
using (SqlCommand command = new SqlCommand())
using (SqlConnection connection = new SqlConnection())
Run Code Online (Sandbox Code Playgroud)
谢谢
是的,有区别.处置SqlCommand不会自动处理SqlConnection与之相关的.您可以通过这种方式泄漏连接,它会干扰ADO.NET连接池; 如果您在此代码运行时查看数据库服务器的活动,您将看到打开但未关闭的新连接.
您应该始终使用第二个版本.事实上,SqlConnection对象是一个,你真的需要到Dispose.你应该尽快处理任何实施的东西IDisposable,但是没有处理它SqlConnection是特别危险的.
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |