「マイクロソフト系技術情報 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。
TransactionScopeクラスは、2相コミットを実現するための.NET 2.0のAPIであり、
内部的には、トランザクション マネージャ(TM)・リソース マネージャ(RM)であるMS-DTCを使用している。
2相コミットの動作確認用サンプル プログラムを用いて、TransactionScopeクラスの利用方法を説明する。
下記は、SQL Server用のデータ アクセス ライブラリである、
SqlClient?を利用した場合のサンプル コード。
private void Two_Phase_Commit(bool flag)
{
TransactionOptions txopt = new TransactionOptions();
txopt.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
//txopt.IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead;
//txopt.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
//txopt.IsolationLevel = System.Transactions.IsolationLevel.Snapshot;
//txopt.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, txopt))
{
using (SqlConnection con = new SqlConnection(@"Data Source=AAA;Initial Catalog=northwind;User ID=xxx;Password=xxx;"))
{
using (SqlCommand com = new SqlCommand())
{
com.Connection = con;
com.CommandText = "insert into table1(bbb) values('データ')";
try
{
con.Open();
com.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
}
using (SqlConnection con = new SqlConnection(@"Data Source=BBB;Initial Catalog=northwind;User ID=xxx;Password=xxx;"))
{
using (SqlCommand com = new SqlCommand())
{
com.Connection = con;
com.CommandText = "insert into table1(bbb) values('データ')";
try
{
con.Open();
com.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
}
if (flag) // flag変数はコミット、ロールバックのテストのための実装
{
scope.Complete();
}
else{ }
}
}
private void Two_Phase_Commit(bool flag)
{
TransactionOptions txopt = new TransactionOptions();
txopt.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
//txopt.IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead;
//txopt.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
//txopt.IsolationLevel = System.Transactions.IsolationLevel.Snapshot;
//txopt.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, txopt))
{
using (OracleConnection con = new OracleConnection(@"User Id=xxx;Password=xxx;Data Source=AAA/orcl;"))
{
using (OracleCommand com = new OracleCommand())
{
com.Connection = con;
com.CommandText = "insert into table1(aaa, bbb) values(1, 'データ')";
try
{
con.Open();
com.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
}
using (OracleConnection con = new OracleConnection(@"User Id=xxx;Password=xxx;Data Source=BBB/orcl;"))
{
using (OracleCommand com = new OracleCommand())
{
com.Connection = con;
com.CommandText = "insert into table1(aaa, bbb) values(1, 'データ')";
try
{
con.Open();
com.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
}
if (flag) // flag変数はコミット、ロールバックのテストのための実装
{
scope.Complete();
}
else{ }
}
}
詳しくはマニュアルなどを参照して下さい。
(コチラを調べてから随分と期間が空いているので、設定方法も変わっていると思われるため)。