【问题标题】:SqlServer Class static methods - Thread SafetySqlServer 类静态方法 - 线程安全
【发布时间】:2011-12-13 12:06:51
【问题描述】:

我创建了一个类来简化我的应用程序中 SQL Server 的使用。

public static class SqlServer
{        
    public static void QueryNoReturn(string ConnectionString, string Query, SqlParameter[] Parameters, bool IsStoredProcedure)
    {
        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            // Create the command to run
            SqlCommand command = new SqlCommand(Query, conn);

            // If we are running a stored procedure
            if (IsStoredProcedure)
                command.CommandType = System.Data.CommandType.StoredProcedure;

            // Add parameters if they exist
            if (Parameters != null)
                command.Parameters.AddRange(Parameters);

            try
            {
                // Open the connection to the database
                conn.Open();

                // Execute the command and assign to the result object
                command.ExecuteNonQuery();

                conn.Close();

                command.Parameters.Clear();
            }
            catch (SqlException sqlex)
            {
                throw new Exception(
                    string.Format("{0} \"{1}\"", IsStoredProcedure ? "Procedure" : "Query", Query),
                    sqlex);
            }
        }
    }
}

如果我每秒多次调用此静态方法(大约 50 次),那么我会看到线程安全问题吗?

我可以轻松地创建一个 Factory 或其他一些特定于实例的对象,但出于简单起见,我选择了这个选项。

【问题讨论】:

  • 注释“//执行命令并赋值给结果对象”坏了(这里没有赋值发生)

标签: c# thread-safety static-methods


【解决方案1】:

由于您没有使用该类的任何共享资源,因此这似乎是“线程安全的”。

这当然忽略了数据库本身的任何并发问题。

您也应该将 SqlCommand 创建包装在 using 语句中。

由于您是在using 语句中创建SqlConnection,因此您无需在其上显式调用Close,因为它会在释放连接时完成。

【讨论】:

    【解决方案2】:

    没有。当您访问共享资源时,您可能会遇到线程安全问题,但您不会这样做(至少在此方法中不会)。

    顺便说一句,将conn.Close(); 移动到finally 子句,这样即使遇到异常,连接也会关闭。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多