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)); }
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); }
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"); } }
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)); }
/// <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"); }); } }
public SetLockStateRequestObject(string deviceId, int channelIndex, string authorizationPin, LockState targetLockState) { DeviceId = deviceId; ChannelIndex = channelIndex; AuthorizationPin = authorizationPin; TargetLockState = targetLockState; }
/// <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"); }); } }
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); }
internal LockService(IDiskService disk, CacheService cache, TimeSpan timeout, Logger log) { _disk = disk; _cache = cache; _log = log; _timeout = timeout; _state = LockState.Unlocked; }
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, });
public void Open() { if (state == LockState.Close) { state = LockState.Opening; animator.Play("Opening"); } }
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)); }
public void Lock() { anim.ResetTrigger("Open"); anim.SetTrigger("Close"); //collider.enabled = true; //keyPassRenderer.material = blue; lockState = LockState.Locked; }
static void CheckRecursionAuthorization(LockState ctstate, LockState desiredState) { // In read mode you can just enter Read recursively if (ctstate == LockState.Read) { throw new LockRecursionException(); } }
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; }
/// <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; }
/// <summary> /// /// </summary> internal void ClearCaches() { Battery = null; Parameters?.Clear(); IncorrectPin = null; state = DeviceState.Disconnected; lockStatus = LockState.Unknown; Location = null; }
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); } }
public bool TryCancel(short key) { bool success = LockState.TryCancel(ref _token); if (success) { OnAssigned(); } return(success); }
/// <summary> /// 设置没有开启倒计时状态 /// </summary> public void SetNoStart() { gameObject.SetActive(true); if (CdImageTrans != null && TimeText != null) { CdImageTrans.gameObject.SetActive(false); TimeText.text = ""; } State = LockState.NOStart; }
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); }
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; }
public void LockLyrics(List <Lyric> lyrics, LockState lockState) { changeHandler?.BeginChange(); foreach (var lyric in lyrics) { lyric.Lock = lockState; } changeHandler?.EndChange(); }
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); }
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(); } } }
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); }
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)); } }
static void CheckRecursionAuthorization (LockState ctstate, LockState desiredState) { // In read mode you can just enter Read recursively if (ctstate == LockState.Read) throw new LockRecursionException (); }
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; }
/// <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(); }
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; }
internal static bool Has (this LockState state, LockState value) { return (state & value) > 0; }