Table of Contents

Class SemaphoreSlimExtensions

Namespace
Plugin.BaseTypeExtensions
Assembly
Plugin.BaseTypeExtensions.dll

Provides extension methods for working with SemaphoreSlim objects, including optional timeout patterns.

public static class SemaphoreSlimExtensions
Inheritance
SemaphoreSlimExtensions
Inherited Members

Methods

WaitBetterAsync(SemaphoreSlim, int?, CancellationToken)

Waits asynchronously to enter the semaphore within an optional timeout period in milliseconds.

public static Task<bool> WaitBetterAsync(this SemaphoreSlim semaphore, int? millisecondsTimeout, CancellationToken cancellationToken = default)

Parameters

semaphore SemaphoreSlim

The semaphore to wait on.

millisecondsTimeout int?

The optional timeout in milliseconds. If null, zero, or negative, the method calls the original WaitAsync (no timeout).

cancellationToken CancellationToken

A cancellation token to observe while waiting for the semaphore.

Returns

Task<bool>

If timeout is null, zero, or negative: returns the result of the original WaitAsync call. Otherwise: returns a task that completes when the semaphore is entered or when the timeout expires.

Remarks

This method provides a convenient way to add optional timeouts to semaphore wait operations. When no timeout is needed, simply pass null and the original WaitAsync is called. This avoids the overhead of timeout monitoring when it's not required.

Exceptions

ArgumentNullException

Thrown when semaphore is null.

OperationCanceledException

Thrown when the operation is canceled via the cancellationToken.

WaitBetterAsync(SemaphoreSlim, TimeSpan?, CancellationToken)

Waits asynchronously to enter the semaphore within an optional timeout period.

public static Task<bool> WaitBetterAsync(this SemaphoreSlim semaphore, TimeSpan? timeout, CancellationToken cancellationToken = default)

Parameters

semaphore SemaphoreSlim

The semaphore to wait on.

timeout TimeSpan?

The optional timeout duration. If null, zero, or negative, the method calls the original WaitAsync (no timeout).

cancellationToken CancellationToken

A cancellation token to observe while waiting for the semaphore.

Returns

Task<bool>

If timeout is null, zero, or negative: returns the result of the original WaitAsync call. Otherwise: returns a task that completes when the semaphore is entered or when the timeout expires.

Remarks

This method provides a convenient way to add optional timeouts to semaphore wait operations. When no timeout is needed, simply pass null and the original WaitAsync is called. This avoids the overhead of timeout monitoring when it's not required.

Exceptions

ArgumentNullException

Thrown when semaphore is null.

OperationCanceledException

Thrown when the operation is canceled via the cancellationToken.