如果在C#中使用TransactionScope類(分布式事務),則須注意如下事項:
1、在項目中引用using System.Transactions命名空間(先要在添加net組件的引用);
2、具體示例如下:

/**//// <summary>
/// 發送消息
/// </summary>
/// <param name="sendUserId"></param>
/// <param name="toUser">格式7FFA3AF2-E74B-4174-8403-5010C53E49A7|userName,7FFA3AF2-E74B-4174-8403-5010C53E49A7|userName</param>
/// <param name="content"></param>
/// <param name="sendedStatus">表示已送</param>
/// <returns></returns>
public static int sendMessage(string sendUserId, string toUser, string content, string sendedStatus)

{
int receiveCount = 0;
TransactionOptions transactionOption = new TransactionOptions();

//設置事務隔離級別
transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;

// 設置事務超時時間為60秒
transactionOption.Timeout = new TimeSpan(0, 0, 60);

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, transactionOption))

{
try

{
//在這里實現事務性工作
//發送消息
insertMessage(sendUserId, toUser, content, sendedStatus);

//在接收信息表中插入記錄
receiveCount += insertReceiveMessage(userids[0], sendUserId, content, "0");
// 沒有錯誤,提交事務
scope.Complete();
}

catch (Exception ex)
{
throw new Exception("發送信息異常,原因:"+ex.Message);
}finally{
//釋放資源
scope.Dispose();
}
}
return receiveCount;
}


3、對MSDTC組件設置:
步驟:
在控制面板--->管理工具--->服務 中,開啟Distributed Transaction Coordinator 服務。
a.控制面板->管理工具->組件服務->計算機->我的電腦->右鍵->屬性
b.選擇MSDTC頁, 確認"使用本地協調器"
c.點擊下方"安全配置"按鈕
d.勾選: "允許網絡DTC訪問","允許遠程客戶端","允許入站","允許出站","不要求進行身份驗證".
e.對于數據庫服務器端, 可選擇"要求對呼叫方驗證"
f.勾選:"啟用事務Internet協議(TIP)事務"。
g.在雙方防火墻中增加MSDTC.exe例外
可用命令行: netsh firewall set allowedprogram %windir%\system32\msdtc.exe MSDTC enable
4、重啟IIS服務器。
posted on 2009-03-17 17:02
aisoft 閱讀(17039)
評論(3) 編輯 收藏 所屬分類:
.NET技術