【转】C# LINQ TO SQL 分布式事务
public class TransactionExtension
{
public static void Excute(params Action[] actions)
{
//ReadCommitted the same as sql server
Excute(System.Transactions.IsolationLevel.ReadCommitted, null, actions);
}
public static void Excute(System.Transactions.IsolationLevel level, params Action[] actions)
{
Excute(level, null, actions);
}
public static void Excute(int timeOut, params Action[] actions)
{
Excute(System.Transactions.IsolationLevel.ReadCommitted, timeOut, actions);
}
public static void Excute(System.Transactions.IsolationLevel level, int? timeOut, params Action[] actions)
{
if (actions == null || actions.Length == 0)
return;
TransactionOptions options = new TransactionOptions();
options.IsolationLevel = level;
//
if (timeOut.HasValue)
options.Timeout = new TimeSpan(0, 0, timeOut.Value); //default for 60 secords
using (TransactionScope tran = new TransactionScope(TransactionScopeOption.Required, options))
{
Array.ForEach<Action>(actions, action => action());
tran.Complete(); //submit
}
}
}
在TransactionScope区域里面所有的ACTION都在这个事务里面。操作可以是同一个数据库,也可以多个数据库(可以不同机器)。
若没有执行 tran.Complete(); //submit 或者在执行 tran.Complete(); 前发生了异常都将产生回滚。
当我们调用的时候我们可以运用
public bool SaveUserGroupToDB(string strContent, string strGroupID, string strSupplier, string strRetailer, string strDescription)
{
string[] stringSeparators;
string[] result;
bool saveResult = false, bl = false;
stringSeparators = new string[] { "##V##" };
result = strContent.Split(stringSeparators,
StringSplitOptions.RemoveEmptyEntries);
try
{
Action action = () =>
{
saveResult = db.SaveUserGroupToDB(strGroupID, strSupplier, strRetailer, strDescription);
};
Action action1 = () =>
{
bl = db.SaveDeminsionAttrToDB(result, strGroupID);
};
TransactionExtension.Excute(action, action1);
return saveResult && bl;
}
catch (Exception ex)
{
myLogger.Error(String.Format("There is an error when saving group {0} to db. ", strGroupID) + ex.Message);
return false;
}
}
在这里ACTION就是一个委托
当action或者 action1失败都将导致整个操作的失败,这样就可以回滚到初始状态。
当看到一些不好的代码时,会发现我还算优秀;当看到优秀的代码时,也才意识到持续学习的重要!--buguge
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/buguge/articles/2290572.html
浙公网安备 33010602011771号