public void Start() { switch (Interlocked.Read(ref this.workerState)) { case WORKER_STATE_INIT: if (InterLockedEx.CompareAndSet(ref this.workerState, WORKER_STATE_STARTED, WORKER_STATE_INIT)) { _workerThread.Start(); } break; case WORKER_STATE_STARTED: break; case WORKER_STATE_SHUTDOWN: throw new HashedWheelTimerException("HashedWheelTimer 不支持的停止以后再次开启。"); default: throw new HashedWheelTimerException("HashedWheelTimer 状态错误。"); } // Wait until the startTime is initialized by the worker. while (startTime == 0) { _startTimeInitialized.Wait(); } }
public IEnumerable <ITimeout> Stop() { if (Thread.CurrentThread == _workerThread) { throw new InvalidOperationException( $"{nameof(HashedWheelTimer)}.{nameof(HashedWheelTimer.Stop)} 不能在 worker 线程被调用。"); } if (!InterLockedEx.CompareAndSet(ref this.workerState, WORKER_STATE_SHUTDOWN, WORKER_STATE_STARTED)) { // workerState can be 0 or 2 at this moment - let it always be 2. Interlocked.Exchange(ref this.workerState, WORKER_STATE_SHUTDOWN); misuseDetector.Decrease(); return(Enumerable.Empty <ITimeout>()); } //等待线程处理完成。 while (_workerThread.IsAlive) { _worker.Stop(); _workerThread.Join(100); } misuseDetector.Decrease(); return(_worker.UnprocessedTimeouts()); }
public bool CompareAndSetState(int expected, int state) { return(InterLockedEx.CompareAndSet(ref this.state, state, expected)); }