Class ModelLibraryTaskHolder<TKey, TResult>
A generic class that provides task deduplication and serialized execution of tasks. Only one task can be executing at a time across all keys. For each key, subsequent calls while a task is in progress will return the result of the ongoing task rather than starting a new one.
This serialized execution is provided by a semaphore that is held for the entire duration of each task, ensuring only one task runs at a time regardless of key. This makes the class suitable for operations that need to be serialized, such as model library tasks that should not run concurrently.
This is a best-effort implementation intended for slow or infrequent operations. It may exhibit race conditions under high concurrency of short-lived tasks or rapid task creation/completion cycles.
public class ModelLibraryTaskHolder<TKey, TResult> : IDisposable
Type Parameters
TKey
TResult
- Inheritance
-
ModelLibraryTaskHolder<TKey, TResult>
- Implements
- Inherited Members
Constructors
ModelLibraryTaskHolder()
Creates a new ModelLibraryTaskHolder<TKey, TResult>.
public ModelLibraryTaskHolder()
Methods
Dispose()
Disposes the task manager and releases all resources.
public void Dispose()
ExecuteAsync(TKey, Func<CancellationToken, Task<TResult>>, CancellationToken)
Executes a task for a given key in a serialized manner, ensuring only one task executes at a time across all keys. If a task for any key is currently executing, new tasks will wait for their turn. For a given key, if a task is already in progress, subsequent calls will return the result of that ongoing task rather than starting a new one.
public Task<TResult> ExecuteAsync(TKey key, Func<CancellationToken, Task<TResult>> taskFactory, CancellationToken token = default)
Parameters
key
TKeyUnique key identifying the task.
taskFactory
Func<CancellationToken, Task<TResult>>Function creating the task. It receives the
token
so it can honour cancellation.token
CancellationTokenCancellation token.
Returns
- Task<TResult>
The task result. Note that the underlying task execution is serialized - only one task runs at a time.
Remarks
The provided taskFactory
must not call back into ExecuteAsync(TKey, Func<CancellationToken, Task<TResult>>, CancellationToken) on the same instance, as this will cause a deadlock.
Exceptions
- ObjectDisposedException
Thrown if the manager has been disposed.