【发布时间】: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