public SystemLock(string?name) { // WaitOne() waits until count > 0 then decrements count // Release() increments count // initial count: the initial count value // maximum count: the max value of count, and then Release() throws if (string.IsNullOrWhiteSpace(name)) { // anonymous semaphore // use one unique releaser, that will not release the semaphore when finalized // because the semaphore is destroyed anyway if the app goes down _semaphore = new SemaphoreSlim(1, 1); // create a local (to the app domain) semaphore _releaser = new SemaphoreSlimReleaser(_semaphore); _releaserTask = Task.FromResult(_releaser); } else { // named semaphore // use dedicated releasers, that will release the semaphore when finalized // because the semaphore is system-wide and we cannot leak counts _semaphore2 = new Semaphore(1, 1, name); // create a system-wide named semaphore } }
/// <inheritdoc /> public void Dispose() { var semaphore = this._semaphoreSlim; this._semaphoreSlim = null; semaphore?.Dispose(); }
public TcpViscaTransport( IPEndPoint endPoint, byte deviceId = 1, uint maxTimeout = 20000, ushort connectionTimeout = 5000, ILogger?logger = null) { if (maxTimeout < 100 || maxTimeout > 86400000) { throw new ArgumentOutOfRangeException(nameof(maxTimeout), maxTimeout, "The maximum timeout must be > 100ms and <= 1 day."); } if (connectionTimeout < 100) { throw new ArgumentOutOfRangeException(nameof(connectionTimeout), connectionTimeout, "The maximum timeout must be > 100ms."); } if (connectionTimeout > maxTimeout) { throw new ArgumentOutOfRangeException(nameof(connectionTimeout), connectionTimeout, "The connection timeout must be <= the maximum timeout."); } _logger = logger; EndPoint = endPoint; DeviceId = deviceId; MaxTimeout = maxTimeout; ConnectionTimeout = connectionTimeout; _connectionState = new BehaviorSubject <bool>(false); // Only allow one command at a time _semaphore = new SemaphoreSlim(1); _buffer = ArrayPool <byte> .Shared.Rent(16); }
private static void CleanupBufferAndSemaphore( Pool <byte[]> .PoolHandle blockBufferHandle, SemaphoreSlim?blockActionSemaphore) { blockBufferHandle.Dispose(); blockActionSemaphore?.Release(); }
private static Task WalkSingleBlockBlobAsync( Stream stream, SemaphoreSlim?blockActionSemaphore, SingleBlockBlobCallbackAsync singleBlockCallback, long bytesLeftInBlob) { return(ReadBlockAsync( stream, blockActionSemaphore, bytesLeftInBlob, async(blockBufferHandle, blockLength, blockHash) => { try { var rollingId = new RollingBlobIdentifierWithBlocks(); var blobIdentifierWithBlocks = rollingId.Finalize(blockHash); await singleBlockCallback(blockBufferHandle.Value, blockLength, blobIdentifierWithBlocks).ConfigureAwait(false); } finally { blockBufferHandle.Dispose(); blockActionSemaphore?.Release(); } })); }
/// <summary> /// Creates the payload bundle. /// </summary> /// <param name="dataObject">The data object.</param> /// <param name="level">The level.</param> /// <param name="custom">The custom.</param> /// <param name="timeout">The timeout.</param> /// <param name="signal">The signal.</param> /// <returns>PayloadBundle.</returns> private PayloadBundle CreatePayloadBundle( object dataObject, ErrorLevel level, IDictionary <string, object?>?custom, TimeSpan?timeout = null, SemaphoreSlim?signal = null ) { DateTime?timeoutAt = null; if (timeout.HasValue) { timeoutAt = DateTime.Now.Add(timeout.Value); } switch (dataObject) { case IRollbarPackage package: if (package.MustApplySynchronously) { package.PackageAsRollbarData(); } return(new PayloadBundle(this, package, level, custom, timeoutAt, signal)); default: return(new PayloadBundle(this, dataObject, level, custom, timeoutAt, signal)); } }
/// <summary> /// Wait for an instance to become available and then get it. /// </summary> public async Task <IPoolToken> GetAsync() { await _objectsAvailable.WaitAsync(); SemaphoreSlim?semaphoreToBeReleased = _objectsAvailable; try { T obj; if (!_objects.TryTake(out obj)) { throw ContractUtilities.AssertFailure("Semaphore was available, but pool is empty."); } var token = new BoundedPoolToken(obj, this); semaphoreToBeReleased = null; return(token); } finally { if (semaphoreToBeReleased != null) { _objectsAvailable.Release(); } } }
/// <summary> /// Starts the thread. /// </summary> public void Start() { if (_currentState != ObjectThreadState.None) { throw new InvalidOperationException("Unable to start thread: Illegal state: " + _currentState + "!"); } //Ensure that one single pass of the main loop is made at once _mainLoopSynchronizeObject.Release(); // Create stop semaphore if (_threadStopSynchronizeObject != null) { _threadStopSynchronizeObject.Dispose(); _threadStopSynchronizeObject = null; } _threadStopSynchronizeObject = new SemaphoreSlim(0); //Go into starting state _currentState = ObjectThreadState.Starting; _mainThread = new Thread(this.ObjectThreadMainMethod) { IsBackground = true, Name = this.Name }; _mainThread.Start(); }
public void Dispose() { if (_semaphore != null) { _semaphore.Release(); _semaphore = null; } }
internal MediatorClient(string name, uint id, bool threadSafe) : base($"{name}{(char)(id + 65)}") { ThreadSafe = threadSafe; if (threadSafe) { pipeSemaphore = new SemaphoreSlim(1, 1); } }
private static async Task ReadBlockAsync( Stream stream, SemaphoreSlim?blockActionSemaphore, long bytesLeftInBlob, BlockReadCompleteAsync readCallback) { if (blockActionSemaphore != null) { await blockActionSemaphore.WaitAsync().ConfigureAwait(false); } bool disposeNeeded = true; try { Pool <byte[]> .PoolHandle blockBufferHandle = GlobalObjectPools.TwoMbByteArrayPool.Get(); try { byte[] blockBuffer = blockBufferHandle.Value; int bytesToRead = (int)Math.Min(BlockSize, bytesLeftInBlob); int bufferOffset = 0; while (bytesToRead > 0) { int bytesRead = await stream.ReadAsync(blockBuffer, bufferOffset, bytesToRead).ConfigureAwait(false); bytesToRead -= bytesRead; bufferOffset += bytesRead; if (bytesRead == 0) { // ReadAsync returns 0 when the stream has ended. if (bytesToRead > 0) { throw new EndOfStreamException(); } } } BlobBlockHash blockHash = HashBlock(blockBuffer, bufferOffset); disposeNeeded = false; // readCallback is now responsible for disposing the blockBufferHandle await readCallback(blockBufferHandle, bufferOffset, blockHash).ConfigureAwait(false); } finally { if (disposeNeeded) { blockBufferHandle.Dispose(); } } } finally { if (disposeNeeded) { blockActionSemaphore?.Release(); } } }
/// <summary> /// Initializes a new instance of the <see cref="LockScope" /> class. /// </summary> /// <param name="gate">The gate.</param> /// <param name="acquired">if set to <c>true</c> [acquired].</param> /// <param name="keepAlive">The keep alive.</param> internal LockScope( SemaphoreSlim gate, bool acquired, AsyncLock keepAlive /* keep alive - avoid disposal */) { _gate = gate; Acquired = acquired; _keepAlive = keepAlive; }
/// <summary> /// Initializes a new instance of the <see cref="PayloadBundle" /> class. /// </summary> /// <param name="rollbarLogger">The rollbar logger.</param> /// <param name="payloadPackage">The payload package.</param> /// <param name="level">The level.</param> /// <param name="timeoutAt">The timeout at.</param> /// <param name="signal">The signal.</param> public PayloadBundle( IRollbar rollbarLogger, IRollbarPackage payloadPackage, ErrorLevel level, DateTime?timeoutAt, SemaphoreSlim?signal ) : this(rollbarLogger, payloadPackage, level, null, timeoutAt, signal) { }
/// <summary> /// Initializes a new instance of the <see cref="PayloadBundle" /> class. /// </summary> /// <param name="rollbarLogger">The rollbar logger.</param> /// <param name="payloadObject">The payload object.</param> /// <param name="level">The level.</param> /// <param name="timeoutAt">The timeout at.</param> /// <param name="signal">The signal.</param> public PayloadBundle( IRollbar rollbarLogger, object payloadObject, ErrorLevel level, DateTime?timeoutAt, SemaphoreSlim?signal ) : this(rollbarLogger, payloadObject, level, null, timeoutAt, signal) { }
internal RateLimiter(RateLimit rateLimit, ILogger <IRateLimiter <T> >?logger) { this._serviceName = $"{typeof(RateLimiter<T>).Name}<{typeof(T).Name}>"; this.RateLimit = rateLimit; this.Logger = logger ?? NullLogger <RateLimiter <T> > .Instance; this._lastUpdateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); this._availablePermits = rateLimit.AmountOfRequests; this._semaphoreSlim = new(1, 1); }
public TiffStreamContentSource(Stream stream, bool leaveOpen) { _stream = stream ?? throw new ArgumentNullException(nameof(stream)); if (!stream.CanSeek) { throw new ArgumentException("Stream must be seekable.", nameof(stream)); } _semaphore = new SemaphoreSlim(1); _reader = new ContentReader(stream, _semaphore); _leaveOpen = leaveOpen; }
/// <summary> /// Enqueues the specified data object. /// </summary> /// <param name="dataObject">The data object.</param> /// <param name="level">The level.</param> /// <param name="custom">The custom.</param> /// <param name="timeout">The timeout.</param> /// <param name="signal">The signal.</param> /// <returns>ILogger.</returns> internal ILogger Enqueue( object dataObject, ErrorLevel level, IDictionary <string, object?>?custom, TimeSpan?timeout = null, SemaphoreSlim?signal = null ) { this.EnqueueData(dataObject, level, custom, timeout, signal); return(this); }
/// <summary> /// Stops the asynchronous. /// </summary> public async Task StopAsync(int timeout) { this.Stop(); if (_threadStopSynchronizeObject != null) { await _threadStopSynchronizeObject.WaitAsync(timeout); _threadStopSynchronizeObject.Dispose(); _threadStopSynchronizeObject = null; } }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <exception cref="ObjectDisposedException">Dispose can be invoked once</exception> public void Dispose() { if (_gate == null) { throw new ObjectDisposedException("Dispose can be invoked once"); } if (Acquired) { _gate?.Release(); } _gate = null; _keepAlive = null; GC.SuppressFinalize(this); }
public override void Initialize(ViewVariablesInstanceObject instance) { base.Initialize(instance); if (instance.Object == null) { DebugTools.Assert(instance.Session != null); _networked = true; _networkSemaphore = new SemaphoreSlim(1, 1); } else { var enumerable = (IEnumerable)instance.Object; _enumerator = enumerable.GetEnumerator(); } var outerVBox = new VBoxContainer(); _controlsHBox = new HBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ShrinkCenter }; { // Page navigational controls. _leftButton = new Button { Text = "<<", Disabled = true }; _pageLabel = new LineEdit { Text = "0", CustomMinimumSize = (60, 0) }; _rightButton = new Button { Text = ">>" }; _leftButton.OnPressed += _leftButtonPressed; _pageLabel.OnTextEntered += _lineEditTextEntered; _rightButton.OnPressed += _rightButtonPressed; _controlsHBox.AddChild(_leftButton); _controlsHBox.AddChild(_pageLabel); _controlsHBox.AddChild(_rightButton); } outerVBox.AddChild(_controlsHBox); _elementsVBox = new VBoxContainer(); outerVBox.AddChild(_elementsVBox); instance.AddTab("IEnumerable", outerVBox); }
public ProducerConsumer(int boundedCapacity) { if (boundedCapacity <= 0 && boundedCapacity != UnboundedCapacity) { throw new ArgumentOutOfRangeException(nameof(boundedCapacity)); } _boundedCapacity = boundedCapacity; if (boundedCapacity != UnboundedCapacity) { _bulkhead = new SemaphoreSlim(boundedCapacity, boundedCapacity); } }
protected override void Dispose(bool disposing) { if (!(_stream is null) && !_leaveOpen) { _stream.Dispose(); } if (!(_semaphore is null)) { _semaphore.Dispose(); _semaphore = null; } _stream = null; _reader = null; }
private static void ReadBlock(Stream stream, SemaphoreSlim?blockActionSemaphore, long bytesLeftInBlob, BlockReadComplete readCallback) { blockActionSemaphore?.Wait(); bool disposeNeeded = true; try { Pool <byte[]> .PoolHandle blockBufferHandle = GlobalObjectPools.TwoMbByteArrayPool.Get(); try { byte[] blockBuffer = blockBufferHandle.Value; int bytesToRead = (int)Math.Min(BlockSize, bytesLeftInBlob); int bufferOffset = 0; while (bytesToRead > 0) { int bytesRead = stream.Read(blockBuffer, bufferOffset, bytesToRead); bytesToRead -= bytesRead; bufferOffset += bytesRead; if (bytesRead == 0) { // ReadAsync returns 0 when the stream has ended. if (bytesToRead > 0) { throw new EndOfStreamException(); } } } BlobBlockHash blockHash = HashBlock(blockBuffer, bufferOffset); disposeNeeded = false; readCallback(blockBufferHandle, bufferOffset, blockHash); } finally { if (disposeNeeded) { blockBufferHandle.Dispose(); } } } finally { if (disposeNeeded) { blockActionSemaphore?.Release(); } } }
public void SetFixedLength() { lock (this.@lock) { if (this.spaceAvailableSignal == null && !this.readerClosed && !this.writerClosed) { this.spaceAvailableSignal = new SemaphoreSlim( initialCount: this.GetSpaceAvailableNoLock() > 0 ? 1 : 0, maxCount: 1 ); } } }
/// <summary> /// Initializes a new instance of the <see cref="PayloadBundle" /> class. /// </summary> /// <param name="rollbarLogger">The rollbar logger.</param> /// <param name="payloadPackage">The payload package.</param> /// <param name="level">The level.</param> /// <param name="custom">The custom.</param> /// <param name="timeoutAt">The timeout at.</param> /// <param name="signal">The signal.</param> public PayloadBundle( IRollbar rollbarLogger, IRollbarPackage payloadPackage, ErrorLevel level, IDictionary <string, object?>?custom, DateTime?timeoutAt, SemaphoreSlim?signal ) : this(rollbarLogger, payloadPackage as object, level, custom, timeoutAt, signal) { if (payloadPackage != null) { IRollbarPackage package = ApplyCustomKeyValueDecorator(payloadPackage); this._rollbarPackage = package; } }
public override async ValueTask DisposeAsync() { if (!(_stream is null) && !_leaveOpen) { await _stream.DisposeAsync().ConfigureAwait(false); _stream = null; } if (!(_semaphore is null)) { _semaphore.Dispose(); _semaphore = null; } await base.DisposeAsync().ConfigureAwait(false); _reader = null; }
async Task WaitForNewBlockAsync(CancellationToken cancellationToken) { this.notification = new SemaphoreSlim(0); try { await this.notification.WaitAsync(cancellationToken); } finally { // We need to synchronize Dispose() and Release() due to it not thread safe. lock (this.notification) { this.notification.Dispose(); } this.notification = null; } }
/// <summary> /// Initializes a new instance of the <see cref="PayloadBundle" /> class. /// </summary> /// <param name="rollbarLogger">The rollbar logger.</param> /// <param name="payloadObject">The payload object.</param> /// <param name="level">The level.</param> /// <param name="custom">The custom.</param> /// <param name="timeoutAt">The timeout at.</param> /// <param name="signal">The signal.</param> public PayloadBundle( IRollbar rollbarLogger, object payloadObject, ErrorLevel level, IDictionary <string, object?>?custom, DateTime?timeoutAt, SemaphoreSlim?signal ) { Assumption.AssertNotNull(rollbarLogger, nameof(rollbarLogger)); Assumption.AssertNotNull(payloadObject, nameof(payloadObject)); this._rollbarLogger = rollbarLogger; this._payloadObject = payloadObject; this._level = level; this._custom = custom; this._timeoutAt = timeoutAt; this._signal = signal; }
/// <summary> /// 进行配置。 /// </summary> /// <typeparam name="TSource">目标源的类型。</typeparam> /// <param name="configure">执行配置的委托。</param> public static void Configure <TSource>(Action <IImageExOptions <TSource> > configure) where TSource : class { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var options = new ImageExOptions <TSource>(); configure(options); if (_throttler == null || _throttlerInitialCount != options.MaxHttpDownloadCount) { _throttler = new SemaphoreSlim(options.MaxHttpDownloadCount); _throttlerInitialCount = options.MaxHttpDownloadCount; } options.Services.AddSingleton(_throttler); Services[typeof(TSource)] = options.Services; }
public async Task SpeakAsync(string text, SpeechOptions?options = default, CancellationToken cancelToken = default) { if (string.IsNullOrEmpty(text)) { throw new ArgumentNullException(nameof(text), "Text cannot be null or empty string"); } if (options?.Volume.HasValue ?? false) { if (options.Volume.Value < VolumeMin || options.Volume.Value > VolumeMax) { throw new ArgumentOutOfRangeException($"Volume must be >= {VolumeMin} and <= {VolumeMax}"); } } if (options?.Pitch.HasValue ?? false) { if (options.Pitch.Value < PitchMin || options.Pitch.Value > PitchMax) { throw new ArgumentOutOfRangeException($"Pitch must be >= {PitchMin} and <= {PitchMin}"); } } if (semaphore == null) { semaphore = new SemaphoreSlim(1, 1); } try { await semaphore.WaitAsync(cancelToken); await PlatformSpeakAsync(text, options, cancelToken); } finally { if (semaphore.CurrentCount == 0) { semaphore.Release(); } } }