#region COPYRIGHT
//
//     THIS IS GENERATED BY TEMPLATE
//     
//     AUTHOR  :     ROYE
//     DATE       :     2010
//
//     COPYRIGHT (C) 2010, TIANXIAHOTEL TECHNOLOGIES CO., LTD. ALL RIGHTS RESERVED.
//
#endregion

using System;
using System.ComponentModel;
using System.Runtime;
using System.Configuration;
using System.Threading;

namespace System.Threading
{
    [TypeDescriptionProvider(typeof(HyperTypeDescriptionProvider)), Serializable]
    public class Lockable : ILockable
    {
        [NonSerialized]
        private readonly static int _SpinCycles = 20;

        [NonSerialized]
        protected static long _Conflicts;

        [NonSerialized]
        protected int _Lock;


        public bool TryAquireLock()
        {
            if (_Lock == 1)
            {
                return false;
            }
            return (Interlocked.CompareExchange(ref _Lock, 1, 0) != 1);
        }

        /// <summary>
        /// 请求锁
        /// </summary>
        public void AquireLock()
        {
            // Assume that we will grab the lock - call CompareExchange
            if (Interlocked.CompareExchange(ref _Lock, 1, 0) == 1)
            {
                int n = 0;

                // Could not grab the lock - spin/wait until the lock looks obtainable
                while (_Lock == 1)
                {
                    if (n++ > _SpinCycles)
                    {
#if TrackConflicts
                        Interlocked.Increment(ref _conflicts);
#endif
                        n = 0;
                        Thread.Sleep(0);
                    }
                }

                // Try to grab the lock - call CompareExchange
                while (Interlocked.CompareExchange(ref _Lock, 1, 0) == 1)
                {
                    n = 0;

                    // Someone else grabbed the lock.  Continue to spin/wait until the lock looks obtainable
                    while (_Lock == 1)
                    {
                        if (n++ > _SpinCycles)
                        {
#if TrackConflicts
                            Interlocked.Increment(ref _conflicts);
#endif
                            n = 0;
                            Thread.Sleep(0);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 释放锁
        /// </summary>
        public void ReleaseLock()
        {
            _Lock = 0;
        }

        /// <summary>
        /// 是否处于锁住状态
        /// </summary>
        public bool Locked
        {
            get { return (_Lock != 0); }
        }

        /// <summary>
        /// 返回已经发生的锁冲突的数量
        /// </summary>
        public static long Conflicts
        {
            get { return _Conflicts; }
        }

    }
}
