2011-12-13 5 views
1

내 응용 프로그램 내에서 SQL Server를 쉽게 사용할 수 있도록 클래스를 만들었습니다.SqlServer 클래스 정적 메서드 - 스레드 안전

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 또는 다른 인스턴스 특정 개체를 만들 수 있지만이 옵션을 단순화했다.

+0

"// 명령을 실행하고 결과 개체에 할당"이라는 설명이 잘못되었습니다 (여기서 할당이 발생하지 않습니다) –

답변

1

아니요. 공유 리소스에 액세스 할 때 스레드 안전 문제가 발생할 수 있지만 그렇게하지는 않습니다 (적어도이 방법은 아님).

그런데 conn.Close();finally 절로 이동하면 예외가 발생해도 연결이 종료됩니다.

2

클래스의 공유 리소스를 사용하지 않으므로 "스레드로부터 안전함"인 것으로 나타납니다.

물론 이것은 데이터베이스 자체의 동시성 문제를 무시합니다.

SqlCommand 작성을 using 문장으로 마무리해야합니다.

당신이 using 문에서 SqlConnection을 만드는 때문에, 당신은 연결이 배치 될 때 완료됩니다 명시 적으로 그것에 Close를 호출 할 필요가 없습니다.