Solution Code One: Use lock lock
//static private static variables are recommended for locksPrivate ReadOnly Static Object_mylock =New Object(); /// <summary> ///transactions, multiple table modifications/// </summary> /// <param name= "name" ></param> /// <returns></returns> Public BOOLUpdateName (stringname) { Lock(_mylock) {using(varTran =NewTransactionScope ()) {Moduleoperate _module=Newmoduleoperate (); 1. Modify the module name _module. Updatefirstname ("module:"+name); 2. Modify Menu This. Updatefirstname ("Menu:"+name); Commit Transaction Tran.complete (); } } return true; }
Solution code Two: Using the Monitor package TransactionScope
using (varnew eftransaction ()) { // Modify name ">>moduleoperate:" + Name; Updatefirstname (name); // 2. Modify the menu New menuoperate (); _menu. Updatefirstname (name); // commit a transaction tran.commit (); }
Eftransaction class Definition:
/// <summary> ///custom transaction processing,///This version, the database context appears multiple, so the transaction uses TransactionScope///use exclusive locks to ensure single-threaded execution of transactions/// </summary> Public classeftransaction:idisposable {Private ReadOnly Static Object_mylock =New Object(); /// <summary> ///Current Transaction Object/// </summary> PrivateTransactionScope Tran =NULL; Publiceftransaction () {monitor.enter (_mylock);//Get exclusive lock This. Tran =NewTransactionScope (); } /// <summary> ///Submit/// </summary> Public voidCommit () {tran.complete (); } /// <summary> ///Roll -back operation, automatic call rollback in Dispose ()/// </summary> Public voidRollback () {//perform release early, roll back if(Tran! =NULL) Tran. Dispose (); } Public voidDispose () {if(Tran! =NULL) Tran. Dispose (); Monitor.Exit (_mylock);//release the exclusive lock } }
Original: http://blog.csdn.net/u011127019/article/details/54576873
EF Multithreading TransactionScope Transaction Exception "Transaction Eftransaction class definition: is deadlocked on the lock resource with another process and has been selected as a deadlock victim. Please rerun the transaction. "