buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

【转】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失败都将导致整个操作的失败,这样就可以回滚到初始状态。

 

转载自:http://hi.baidu.com/jxnuwzp/home

posted on 2011-12-16 18:39  buguge  阅读(426)  评论(0)    收藏  举报