Action<Transaction, string> action = (t, str) =>
{
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=chen;database=pubs");
con.Open();
if(null != con)
con.EnlistTransaction(t);
string strSql = "insert into test values('" + str + "','zzz','zzz')";
SqlCommand cmd = new SqlCommand(strSql, con);
Console.WriteLine(cmd.ExecuteNonQuery());
con.Close();
};
using(CommittableTransaction ctran =new CommittableTransaction())
{
try
{
action(ctran, "123645");
ctran.Commit();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
ctran.Rollback();
}
}
//依赖事务处理
Action<object> DepAction= t =>
{
DependentTransaction de = t as DependentTransaction;
action(de, DateTime.Now.Second.ToString());
Thread.Sleep(3000);
de.Rollback();
};
using(CommittableTransaction ctran = new CommittableTransaction())
{
try
{
action(ctran, DateTime.Now.Second.ToString() + "Com");
new Thread(delegate(object obj) { DepAction(obj); }).Start(ctran.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
/*
* BlockCommitUntilComplete 跟事务Commit之前,等待所有依赖事务提交
* RollbackIfNotComplete 跟事务Commit时,依赖事务没有提交,则终止整个事务
*/
ctran.Commit();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
ctran.Rollback();
}
}
//环境事务处理
using(TransactionScope scope = new TransactionScope())
{
Transaction.Current.TransactionCompleted += (s, e) => {
Console.WriteLine(e.Transaction.TransactionInformation.ToString());
};
scope.Dispose();
}