transactional.cs

来自「C#高级编程第6版随书源代码 值得下载」· CS 代码 · 共 97 行

CS
97
字号
using System.Diagnostics;
using System.Transactions;

namespace Wrox.ProCSharp.Transactions
{
    public partial class Transactional<T> 
    {
        private T liveValue;
        private ResourceManager<T> enlistment;
        private Transaction enlistedTransaction;

        internal void Commit(T value, Transaction tx)
        {
            liveValue = value;
            enlistedTransaction = null;
            
        }

        internal void Rollback(Transaction tx)
        {
            enlistedTransaction = null;
        }

        private ResourceManager<T> GetEnlistment()
        {
            Transaction tx = Transaction.Current;
            Trace.Assert(tx != null, "Must be invoked with ambient transaction");

            if (enlistedTransaction == null)
            {
                enlistment = new ResourceManager<T>(this, tx);
                tx.EnlistVolatile(enlistment, EnlistmentOptions.None);
                enlistedTransaction = tx;
                return enlistment;
            }
            else if (enlistedTransaction == Transaction.Current)
            {
                return enlistment;
            }
            else
            {
                throw new TransactionException("This class only supports enlisting with one transaction");
            }


        }

        public Transactional(T value)
        {
            if (Transaction.Current == null)
            {
                this.liveValue = value;
            }
            else
            {
                this.liveValue = default(T);
                GetEnlistment().Value = value;
            }
        }

        public Transactional() 
            : this(default(T)) {}

        public T Value
        {
            get { return GetValue(); }
            set { SetValue(value); }
        }

        protected virtual T GetValue()
        {
            if (Transaction.Current == null)
            {
                return liveValue;
            }
            else
            {
                return GetEnlistment().Value;
            }

        }

        protected virtual void SetValue(T value)
        {
            if (Transaction.Current == null)
            {
                liveValue = value;
            }
            else 
            {
                GetEnlistment().Value = value;
            }
        }

    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?