AsyncUpdateThrottle<T> Class

Namespace
Kampute.HttpClient.Utilities
Assembly
  • Kampute.HttpClient.dll

Definition

Holds a value that is updated asynchronously, and skips an update when another one completed while it waited.
public sealed class AsyncUpdateThrottle<T> : IDisposable
Inheritance
Implements

Type Parameters

T
The type of the value. An immutable type is safest, because the value is shared between threads.

Remarks

Updates run one at a time. When several callers request an update at the same time, such as requests that all find an access token expired, the first one runs and the others return without running their update, because the value changed after they asked. This suits values that are costly to obtain.

Constructors

AsyncUpdateThrottle<T>()

Initializes a new instance of the AsyncUpdateThrottle<T> class with the default value of T.
public AsyncUpdateThrottle<T>()

AsyncUpdateThrottle<T>(T)

Initializes a new instance of the AsyncUpdateThrottle<T> class with the specified value.
public AsyncUpdateThrottle<T>(T initialValue)

Parameters

initialValue T
The initial value.

Properties

LastUpdateTime

Gets the time of the last completed update.
public DateTimeOffset LastUpdateTime { get; }

Property Value

DateTimeOffset
The time, in UTC, when the last update completed, or DateTimeOffset.MinValue if none has completed.

Value

Gets the current value.
public T Value { get; }

Property Value

T
The value of the last completed update, or the initial value if none has completed. It can be read from any thread.

Methods

Dispose()

Releases the lock that serializes the updates.
public void Dispose()

TryUpdateAsync(Func<Task<T>>, CancellationToken)

Updates the value with the result of a function, unless another update completes after this method is called.
public Task<bool> TryUpdateAsync(Func<Task<T>> asyncUpdater, CancellationToken cancellationToken = default)

Parameters

asyncUpdater Func<Task<T>>
The function that produces the new value.
cancellationToken CancellationToken optional
A token for canceling the wait for an update in progress.

Returns

Task<bool>
A task that resolves to true if asyncUpdater ran and its result became the value, or false if another update completed first and asyncUpdater did not run.

Exceptions

ArgumentNullException
Thrown if asyncUpdater is null.
OperationCanceledException
Thrown if cancellationToken is canceled while the method waits for an update in progress.

Remarks

If asyncUpdater throws, the value is unchanged and the exception propagates to the caller.