c# - 如果在 C# 中的 Using 语句中调用连接关闭事件会发生什么

标签 c# sql

我的假设是,如果 Sqlconnection 在 Using 语句中打开 With,dispose 事件将在语句执行后自动发生,如果我在 Using 语句中强制关闭连接,将会发生什么糟糕的事情练习 ?

using (SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["Constring"]))
{
    // SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["Constring"]);
    conn.Open();

    String query = String.Empty;
    query = "exec " + StoredProcedure + " " + sampleproc + "";

    using (SqlDataAdapter mainTableAdapter = new SqlDataAdapter(query, conn))
    {
        System.Data.DataSet mainTableDS = new System.Data.DataSet();
        mainTableAdapter.Fill(mainTableDS);

        conn.Close();
        mainTableAdapter.Dispose();
        conn.Dispose();

        return mainTableDS;
    }
}

最佳答案

  1. 无需同时调用 Close()Dispose();调用 Dispose() 将自动关闭连接并释放对象。

  2. 无需在 using block 内调用 Close()Dispose()using 语句自动处理对象(并且由于上面的 #1 也关闭了连接)。

此外,关于上面的#2 的注释。如果 Microsoft 的 guidance is followed 多次调用 Dispose() 应该是安全的应该 :

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

关于c# - 如果在 C# 中的 Using 语句中调用连接关闭事件会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388062/

相关文章:

c# - MVC3 应用程序无法在虚拟目录中的 IIS7.5 上运行

mysql - 添加具有别名值的条件

sql - 在 Impala 中将 YYYYMMDD 字符串转换为日期

sql - 如何在 T-SQL 中编写一个函数,该函数接受表作为输入并将结果作为表返回?

c# - 为什么 '+' + 短转换为 44

c# - WPF 本地化扩展

java - 根据学生的分数为学生创建文字注释

SQL LIKE 条件检查整数?

c# - .NET Framework 从 3.5 升级到 4.6 后 C/C++ DLL 失败

c# - 并行 http 请求