TransactionScope の使用に問題があります。TransactionScope は、データ アクセス レイヤー全体でトランザクションを使用するための非常に優れた柔軟性を提供します。このようにして、暗黙的または明示的なトランザクションを使用できます。ADO.NET トランザクションで再びパフォーマンスが向上しますが、現時点ではこれは大きな問題ではありません。ただし、ロックに問題があります。以下のコード例では、分離レベルが ReadCommitted に設定されていますが、テーブル全体がロックされているため、メイン トランザクション (Main メソッド内) がコミットされるまで、テーブル testTable に対して他のクライアントから Select SQL ステートメントを作成することはできません。また、すべてのメソッドで 1 つの接続のみを使用しようとしましたが、動作は同じでした。DBMS は SQL Server 2008 です。何かわからないことはありますか?
よろしく アントン・カルシック
このサンプル コードを参照してください。
class Program
{
public class DAL
{
private const string _connectionString = @"Data Source=localhost\fsdf;Initial Catalog=fasdfsa;Integrated Security=SSPI;";
private const string inserttStr = @"INSERT INTO dbo.testTable (test) VALUES(@test);";
/// <summary>
/// Execute command on DBMS.
/// </summary>
/// <param name="command">Command to execute.</param>
private void ExecuteNonQuery(IDbCommand command)
{
if (command == null)
throw new ArgumentNullException("Parameter 'command' can't be null!");
using (IDbConnection connection = new SqlConnection(_connectionString))
{
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
}
}
public void FirstMethod()
{
IDbCommand command = new SqlCommand(inserttStr);
command.Parameters.Add(new SqlParameter("@test", "Hello1"));
using (TransactionScope sc = new TransactionScope(TransactionScopeOption.Required))
{
ExecuteNonQuery(command);
sc.Complete();
}
}
public void SecondMethod()
{
IDbCommand command = new SqlCommand(inserttStr);
command.Parameters.Add(new SqlParameter("@test", "Hello2"));
using (TransactionScope sc = new TransactionScope(TransactionScopeOption.Required))
{
ExecuteNonQuery(command);
sc.Complete();
}
}
}
static void Main(string[] args)
{
DAL dal = new DAL();
TransactionOptions tso = new TransactionOptions();
tso.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
using (TransactionScope sc = new TransactionScope(TransactionScopeOption.Required,tso))
{
dal.FirstMethod();
dal.SecondMethod();
sc.Complete();
}
}
}