コード例 #1
0
ファイル: AsyncKeyedLock.cs プロジェクト: schotime/bundling
        private void WriterRelease(TKey key)
        {
            TaskCompletionSource <IDisposable> toWake;
            var toWakeIsWriter = false;

            lock (_locks)
            {
                LockState @lock = GetOrCreate(key);

                if (@lock.WaitingWriters.Count > 0)
                {
                    toWake         = @lock.WaitingWriters.Dequeue();
                    toWakeIsWriter = true;
                }
                else if (@lock.WaitingReaderCount > 0)
                {
                    toWake                   = @lock.WaitingReader;
                    @lock.Status             = @lock.WaitingReaderCount;
                    @lock.WaitingReaderCount = 0;
                    @lock.WaitingReader      = new TaskCompletionSource <IDisposable>(TaskCreationOptions.RunContinuationsAsynchronously);
                    _locks[key]              = @lock;
                }
                else
                {
                    Remove(key);
                    return;
                }
            }

            toWake.SetResult(new Releaser(this, key, toWakeIsWriter));
        }
コード例 #2
0
        bool CheckState(ThreadLockState state, int millisecondsTimeout, LockState validState)
        {
            if (disposed)
            {
                throw new ObjectDisposedException("ReaderWriterLockSlim");
            }

            if (millisecondsTimeout < -1)
            {
                throw new ArgumentOutOfRangeException("millisecondsTimeout");
            }

            // Detect and prevent recursion
            LockState ctstate = state.LockState;

            if (ctstate != LockState.None && noRecursion && (!ctstate.Has(LockState.Upgradable) || validState == LockState.Upgradable))
            {
                throw new LockRecursionException("The current thread has already a lock and recursion isn't supported");
            }

            if (noRecursion)
            {
                return(false);
            }

            // If we already had right lock state, just return
            if (ctstate.Has(validState))
            {
                return(true);
            }

            CheckRecursionAuthorization(ctstate, validState);

            return(false);
        }
コード例 #3
0
        private void Release(int token, bool demandMatch = true)
        {
            void ThrowInvalidLockHolder() => throw new InvalidOperationException("Attempt to release a MutexSlim lock token that was not held");

            // release the token (we can check for wrongness without needing the lock, note)
            Log($"attempting to release token {LockState.ToString(token)}");
            if (Interlocked.CompareExchange(ref _token, LockState.ChangeState(token, LockState.Pending), token) != token)
            {
                Log($"token {LockState.ToString(token)} is invalid");
                if (demandMatch)
                {
                    ThrowInvalidLockHolder();
                }
                return;
            }


            if (_mayHavePendingItems)
            {
                ActivateNextQueueItem();
            }
            else
            {
                Log($"no pending items to activate");
            }
        }
コード例 #4
0
ファイル: AsyncKeyedLock.cs プロジェクト: schotime/bundling
        private void ReaderRelease(TKey key)
        {
            TaskCompletionSource <IDisposable> toWake;

            lock (_locks)
            {
                LockState @lock = GetOrCreate(key);

                [email protected];
                if (@lock.Status != 0)
                {
                    _locks[key] = @lock;
                    return;
                }
                else if (@lock.WaitingWriters.Count > 0)
                {
                    @lock.Status = -1;
                    _locks[key]  = @lock;

                    toWake = @lock.WaitingWriters.Dequeue();
                }
                else
                {
                    Remove(key);
                    return;
                }
            }

            toWake.SetResult(new Releaser(this, key, isWriter: true));
        }
コード例 #5
0
        /// <summary>
        /// Try enter in shared lock (read) - Call action if request a new lock
        /// [Non ThreadSafe]
        /// </summary>
        private Action LockShared()
        {
            lock (_disk)
            {
                if (_state != LockState.Unlocked)
                {
                    return () => { }
                }
                ;

                _disk.Lock(LockState.Shared, _timeout);

                _state  = LockState.Shared;
                _shared = true;

                _log.Write(Logger.LOCK, "entered in shared lock mode");

                this.AvoidDirtyRead();

                return(() =>
                {
                    _shared = false;
                    _disk.Unlock(LockState.Shared);
                    _state = LockState.Unlocked;

                    _log.Write(Logger.LOCK, "exited shared lock mode");
                });
            }
        }
コード例 #6
0
 public SetLockStateRequestObject(string deviceId, int channelIndex, string authorizationPin, LockState targetLockState)
 {
     DeviceId         = deviceId;
     ChannelIndex     = channelIndex;
     AuthorizationPin = authorizationPin;
     TargetLockState  = targetLockState;
 }
コード例 #7
0
        /// <summary>
        /// Try enter in reserved mode (read - single reserved)
        /// [ThreadSafe] (always inside an Write())
        /// </summary>
        private Action LockReserved()
        {
            lock (_disk)
            {
                if (_state == LockState.Reserved)
                {
                    return () => { }
                }
                ;

                _disk.Lock(LockState.Reserved, _timeout);

                _state = LockState.Reserved;

                _log.Write(Logger.LOCK, "entered in reserved lock mode");

                // can be a new lock, calls action to notifify
                if (!_shared)
                {
                    this.AvoidDirtyRead();
                }

                // is new lock only when not came from a shared lock
                return(() =>
                {
                    _disk.Unlock(LockState.Reserved);

                    _state = _shared ? LockState.Shared : LockState.Unlocked;

                    _log.Write(Logger.LOCK, "exited reserved lock mode");
                });
            }
        }
コード例 #8
0
            public static bool TrySetResult(ref int token, int value)
            {
                int oldValue = Volatile.Read(ref token);

                return(LockState.GetState(oldValue) == LockState.Pending &&
                       Interlocked.CompareExchange(ref token, value, oldValue) == oldValue);
            }
コード例 #9
0
 internal LockService(IDiskService disk, CacheService cache, TimeSpan timeout, Logger log)
 {
     _disk    = disk;
     _cache   = cache;
     _log     = log;
     _timeout = timeout;
     _state   = LockState.Unlocked;
 }
コード例 #10
0
 public static ValueTaskSourceStatus GetStatus(ref int token)
 {
     return((LockState.GetState(Volatile.Read(ref token))) switch
     {
         LockState.Canceled => ValueTaskSourceStatus.Canceled,
         LockState.Pending => ValueTaskSourceStatus.Pending,
         _ => ValueTaskSourceStatus.Succeeded,
     });
コード例 #11
0
ファイル: Lock.cs プロジェクト: Rahsay/2D-Platformer
 public void Open()
 {
     if (state == LockState.Close)
     {
         state = LockState.Opening;
         animator.Play("Opening");
     }
 }
コード例 #12
0
ファイル: LockDAL.cs プロジェクト: irfanahm3d/SmartLock
        public bool ModifyLockState(int lockId, int userId, LockState state)
        {
            // check if user is allowed to change the state of the
            // lock (should happen in data layer).


            return(this.lockDataLayer.ModifyLockState(lockId, userId, state));
        }
コード例 #13
0
 public void Lock()
 {
     anim.ResetTrigger("Open");
     anim.SetTrigger("Close");
     //collider.enabled = true;
     //keyPassRenderer.material = blue;
     lockState = LockState.Locked;
 }
コード例 #14
0
 static void CheckRecursionAuthorization(LockState ctstate, LockState desiredState)
 {
     // In read mode you can just enter Read recursively
     if (ctstate == LockState.Read)
     {
         throw new LockRecursionException();
     }
 }
コード例 #15
0
    public void InitializeDoor(Grid _grid, LockState _lockState, Vector2 _position, Key _keyRequired)
    {
        grid = _grid;

        positionToSet    = _position;
        gridPosition     = new Vector2(Mathf.FloorToInt(positionToSet.x / 16), Mathf.FloorToInt(positionToSet.y / 16));
        KeyRequired      = _keyRequired;
        currentLockState = _lockState;
    }
コード例 #16
0
        /// <summary>
        /// Convenience function for safe lock state change
        /// </summary>
        /// <param name="newState">New state.</param>
        /// <param name="blockingState">Blocking state.</param>
        protected void TrySetLockState(LockState newState, LockState blockingState = LockState.PreviouslyUnlocked)
        {
            if (m_LockState == blockingState)
            {
                return;
            }

            m_LockState = newState;
        }
コード例 #17
0
 /// <summary>
 ///
 /// </summary>
 internal void ClearCaches()
 {
     Battery = null;
     Parameters?.Clear();
     IncorrectPin = null;
     state        = DeviceState.Disconnected;
     lockStatus   = LockState.Unknown;
     Location     = null;
 }
コード例 #18
0
ファイル: LockResponse.cs プロジェクト: noahvans/HiveThrift
        public void Read(TProtocol iprot)
        {
            bool   isset_lockid = false;
            bool   isset_state  = false;
            TField field;

            iprot.ReadStructBegin();
            while (true)
            {
                field = iprot.ReadFieldBegin();
                if (field.Type == TType.Stop)
                {
                    break;
                }
                switch (field.ID)
                {
                case 1:
                    if (field.Type == TType.I64)
                    {
                        Lockid       = iprot.ReadI64();
                        isset_lockid = true;
                    }
                    else
                    {
                        TProtocolUtil.Skip(iprot, field.Type);
                    }
                    break;

                case 2:
                    if (field.Type == TType.I32)
                    {
                        State       = (LockState)iprot.ReadI32();
                        isset_state = true;
                    }
                    else
                    {
                        TProtocolUtil.Skip(iprot, field.Type);
                    }
                    break;

                default:
                    TProtocolUtil.Skip(iprot, field.Type);
                    break;
                }
                iprot.ReadFieldEnd();
            }
            iprot.ReadStructEnd();
            if (!isset_lockid)
            {
                throw new TProtocolException(TProtocolException.INVALID_DATA);
            }
            if (!isset_state)
            {
                throw new TProtocolException(TProtocolException.INVALID_DATA);
            }
        }
コード例 #19
0
            public bool TryCancel(short key)
            {
                bool success = LockState.TryCancel(ref _token);

                if (success)
                {
                    OnAssigned();
                }
                return(success);
            }
コード例 #20
0
 /// <summary>
 /// 设置没有开启倒计时状态
 /// </summary>
 public void SetNoStart()
 {
     gameObject.SetActive(true);
     if (CdImageTrans != null && TimeText != null)
     {
         CdImageTrans.gameObject.SetActive(false);
         TimeText.text = "";
     }
     State = LockState.NOStart;
 }
コード例 #21
0
            internal LockToken AssertNotCanceled()
            {
                if (LockState.IsCanceled(_token))
                {
                    ThrowCanceled();
                }
                return(this);

                void ThrowCanceled() => throw new TaskCanceledException();
            }
            bool IPendingLockToken.TryCancel(short key)
            {
                bool success = LockState.TryCancel(ref _token);

                if (success)
                {
                    OnAssigned();
                }
                return(success);
            }
            bool IPendingLockToken.TrySetResult(short key, int token)
            {
                bool success = LockState.TrySetResult(ref _token, token);

                if (success)
                {
                    OnAssigned();
                }
                return(success);
            }
コード例 #24
0
 public ShowLocksResponseElement(long lockid, string dbname, LockState state, LockType type, long lastheartbeat, string user, string hostname)
     : this()
 {
     this.Lockid        = lockid;
     this.Dbname        = dbname;
     this.State         = state;
     this.Type          = type;
     this.Lastheartbeat = lastheartbeat;
     this.User          = user;
     this.Hostname      = hostname;
 }
コード例 #25
0
ファイル: LyricManager.cs プロジェクト: karaoke-dev/karaoke
        public void LockLyrics(List <Lyric> lyrics, LockState lockState)
        {
            changeHandler?.BeginChange();

            foreach (var lyric in lyrics)
            {
                lyric.Lock = lockState;
            }

            changeHandler?.EndChange();
        }
コード例 #26
0
ファイル: LockProtectorTests.cs プロジェクト: Poltuu/KeySmith
        public void EnsureDisposeWorks()
        {
            var library = new Mock <IScriptLibrary>();

            using var context = new LockState(new Key("", "", TimeSpan.FromSeconds(1)), "id", CancellationToken.None);

            using (var protector = new LockProtector(library.Object, context))
            {
            }

            Assert.Equal(State.Done, context.State);
        }
コード例 #27
0
        private void ActivateNextQueueItemWithValidatedToken(int token)
        {
            // see if we can nudge the next waiter
            lock (_queue)
            {
                if (Volatile.Read(ref _token) != token)
                {
                    Throw.InvalidLockHolder();
                }

                try
                {
                    if (_queue.Count == 0)
                    {
                        Log($"no pending items to activate");
                        return;
                    }

                    // there's work to do; get a new token
                    Log($"pending items: {_queue.Count}");

                    // we're expecting to activate; get a new token speculatively
                    // (needs to be new so the old caller can't double-dispose and
                    // release someone else's lock)
                    Volatile.Write(ref _token, token = LockState.GetNextToken(token));

                    // try to give the new token to someone
                    while (_queue.Count != 0)
                    {
                        var next = DequeueInsideLock();
                        if (next.TrySetResult(token))
                        {
                            Log($"handed lock to {next}");
                            token = 0; // so we don't release the token
                            return;
                        }
                        else
                        {
                            Log($"lock rejected by {next}");
                        }
                    }
                }
                finally
                {
                    if (token != 0) // nobody actually wanted it; return it
                    {               // (this could be the original token, or a new speculative token)
                        Log("returning unwanted lock");
                        Volatile.Write(ref _token, LockState.ChangeState(token, LockState.Pending));
                    }
                    SetNextAsyncTimeoutInsideLock();
                }
            }
        }
コード例 #28
0
        public static Location ToLocation(this SPSite site, string parentId)
        {
            LockState lockState = LockState.NotLocked;

            var id = site.ID;

            string displayName;
            int    childCount;
            Guid?  databaseId;

            if (site.IsReadLocked)
            {
                lockState = LockState.NoAccess;

                displayName = string.Format(
                    "Site is Locked! {0}",
                    site.Url
                    );
                childCount = 0;

                databaseId = null; //TODO: find out, if dbid can be read when site collection locked
            }
            else
            {
                if (site.RootWeb != null)
                {
                    // TODO: check lock status https://technet.microsoft.com/en-us/library/ff631148(v=office.14).aspx
                    // site.IsReadLocked --> No access
                    displayName = site.RootWeb.Title;
                }
                else
                {
                    displayName = "Site has no root web!"; // well, that's normally impossible, but you never know ...
                }

                childCount = site.AllWebs.Count;

                databaseId = site.ContentDatabase.Id;
            }

            var location = LocationFactory.GetLocation(
                id,
                displayName,
                parentId,
                Scope.Site,
                site.Url,
                childCount,
                databaseId,
                lockState
                );

            return(location);
        }
コード例 #29
0
        public ReplaySingleRegister(
            string name,
            byte defaultValue,
            LockState defaultLockState,
            ISingleRegister?impl = null)
        {
            this.name_             = name;
            this.defaultValue_     = defaultValue;
            this.defaultLockState_ = defaultLockState;
            this.impl_             = impl ?? new SingleRegister();

            this.Reset();
        }
            private void OnAssignedImpl() // make sure this happens on the
            {                             // scheduler's thread to avoid the release thread being stolen
                var token = LockState.GetResult(ref _token);

                if (LockState.GetState(token) == LockState.Canceled)
                {
                    TrySetCanceled();
                }
                else
                {
                    TrySetResult(new LockToken(_mutex, token));
                }
            }
コード例 #31
0
ファイル: ReaderWriterLockSlim.cs プロジェクト: Indifer/Test
		static void CheckRecursionAuthorization (LockState ctstate, LockState desiredState)
		{
			// In read mode you can just enter Read recursively
			if (ctstate == LockState.Read)
				throw new LockRecursionException ();				
		}
コード例 #32
0
ファイル: ReaderWriterLockSlim.cs プロジェクト: Indifer/Test
		bool CheckState (ThreadLockState state, int millisecondsTimeout, LockState validState)
		{
			if (disposed)
				throw new ObjectDisposedException ("ReaderWriterLockSlim");

			if (millisecondsTimeout < -1)
				throw new ArgumentOutOfRangeException ("millisecondsTimeout");

			// Detect and prevent recursion
			LockState ctstate = state.LockState;

			if (ctstate != LockState.None && noRecursion && (!ctstate.Has (LockState.Upgradable) || validState == LockState.Upgradable))
				throw new LockRecursionException ("The current thread has already a lock and recursion isn't supported");

			if (noRecursion)
				return false;

			// If we already had right lock state, just return
			if (ctstate.Has (validState))
				return true;

			CheckRecursionAuthorization (ctstate, validState);

			return false;
		}
コード例 #33
0
        /// <summary>
        /// Parse the RopSpoolerLockMessageRequest structure.
        /// </summary>
        /// <param name="s">An stream containing RopSpoolerLockMessageRequest structure.</param>
        public override void Parse(Stream s)
        {
            base.Parse(s);

            this.RopId = (RopIdType)ReadByte();
            this.LogonId = ReadByte();
            this.InputHandleIndex = ReadByte();
            this.MessageId = new MessageID();
            this.MessageId.Parse(s);
            this.LockState = (LockState)ReadByte();
        }
コード例 #34
0
        private List<XElement> GetContentForLockState(LockState state)
        {
            List<XElement> content = new List<XElement>();

            foreach (XElement el in _areaLevelData[_currentArea].ContentToUnlockOnCompletion.Elements("unlockable"))
            {
                switch (state)
                {
                    case LockState.Locked:
                        if (!(bool)el.Attribute("unlocked")) { content.Add(el); }
                        break;
                    case LockState.Unlocked:
                        if (((bool)el.Attribute("unlocked")) && (!_newlyUnlockedItems.Contains(el))) { content.Add(el); }
                        break;
                    case LockState.NewlyUnlocked:
                        if (((bool)el.Attribute("unlocked")) && (_newlyUnlockedItems.Contains(el))) { content.Add(el); }
                        break;
                    case LockState.FullVersionOnly:
                        if (!(bool)el.Attribute("unlocked")) { content.Add(el); }
                        break;

                }
            }

            return content;
        }
コード例 #35
0
		internal static bool Has (this LockState state, LockState value)
		{
			return (state & value) > 0;
		}