TransactionScope事务操作

  using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    InsertUserBase(); //它插入不成功,自己回滚

                    UserInfos userInfo = new UserInfos
                    {
                        UserID = "1",
                        RealName = "zzl",
                    };
                    db.UserInfos.InsertOnSubmit(userInfo);
                    db.SubmitChanges();

                    trans.Complete();
                }
                catch (Exception)
                {

                    // throw;
                }
                finally
                {
                    trans.Dispose();
                }
            }
            #endregion

  static bool InsertUserBase()
        {

            bool flag;
            try
            {
                UserBases userbase = new UserBases
                {
                    UserID = "0005",
                    Name = "zzl",
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                };
                db.UserBases.InsertOnSubmit(userbase);
                db.SubmitChanges();
                flag = true;
            }
            catch (Exception)
            {

                throw;
            }
            return flag;

        }

InsertUserBase()只要出现异常,程序将自己回滚

 

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions
                {
                    IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,
                    Timeout = new TimeSpan(0, 10, 0) 
                }, TransactionScopeAsyncFlowOption.Enabled))

 

one or more errors occurred(The current TransactionScope is already complete)

如果你正在使用TransactionScope和async/await在一起,你真的应该升级到4.5.1 .NET马上。
一个TransactionScope包装异步代码需要指定TransactionScopeAsyncFlowOption.Enabled在其构造。

TransactionOptions option = new TransactionOptions() { Timeout = new TimeSpan(0, 10, 0), IsolationLevel = IsolationLevel.ReadCommitted };
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option, TransactionScopeAsyncFlowOption.Enabled))

 

posted @ 2020-01-07 12:31  BloggerSb  阅读(250)  评论(0)    收藏  举报