A lightweight library providing extension methods for Task, Task<T>, ValueTask, and ValueTask<T> to simplify asynchronous programming patterns in .NET applications.
Part of the Daily DevOps & .NET - NetEvolve project, which aims to provide a set of useful libraries for .NET developers.
dotnet add package NetEvolve.Extensions.Tasks- WhenAll for ValueTask: Aggregate multiple
ValueTaskorValueTask<T>operations similar toTask.WhenAll - Timeout Support: Execute async operations with configurable timeout handling
- Multi-Framework Support: Compatible with .NET Standard 2.0, .NET 6.0, .NET 7.0, .NET 8.0, .NET 9.0, and .NET 10.0
- Lightweight: Minimal dependencies, focused on essential functionality
- Modern: Supports both
TaskandValueTaskpatterns
Aggregate multiple ValueTask operations, similar to Task.WhenAll. This is useful when you have multiple ValueTask instances that you want to await together.
Note
The ValueTask.WhenAll(...) syntax uses C# 14 extension members (default from .NET 10, otherwise set <LangVersion>14</LangVersion>). With older language versions call ValueTaskExtensions.WhenAll(...) instead. With C# 12 or older, two or three ValueTask<T> arguments of the same result type need explicit type arguments: ValueTaskExtensions.WhenAll<int>(a, b) returns int[], ValueTaskExtensions.WhenAll<int, int>(a, b) returns a tuple. From C# 13 on, the call without type arguments returns int[].
using NetEvolve.Extensions.Tasks;
await ValueTask.WhenAll(
DoSomethingAsync(),
DoSomethingElseAsync(),
DoAnotherThingAsync()
);
Console.WriteLine("All operations completed");using NetEvolve.Extensions.Tasks;
var tasks = new List<ValueTask>
{
ProcessItemAsync(1),
ProcessItemAsync(2),
ProcessItemAsync(3)
};
await ValueTask.WhenAll(tasks);using NetEvolve.Extensions.Tasks;
var results = await ValueTask<int>.WhenAll(
GetValueAsync(1),
GetValueAsync(2),
GetValueAsync(3)
);
// results is int[] { 1, 2, 3 } - results are returned in the same order as tasks
foreach (var result in results)
{
Console.WriteLine(result);
}using NetEvolve.Extensions.Tasks;
IEnumerable<ValueTask<string>> tasks = GetTasksAsync();
string[] results = await ValueTask<string>.WhenAll(tasks);For two or three tasks, dedicated overloads are used automatically. They do not allocate an argument array.
using NetEvolve.Extensions.Tasks;
await ValueTask.WhenAll(DoSomethingAsync(), DoSomethingElseAsync());
int[] results = await ValueTask<int>.WhenAll(GetValueAsync(1), GetValueAsync(2));Await two to four ValueTask<T> instances with different result types and receive the results as a tuple, in input order.
using NetEvolve.Extensions.Tasks;
var (user, orderCount) = await ValueTask.WhenAll(GetUserAsync(), GetOrderCountAsync());
var (name, age, isActive, score) = await ValueTask.WhenAll(
GetNameAsync(),
GetAgeAsync(),
GetIsActiveAsync(),
GetScoreAsync()
);Note
The receiver type decides the result shape. ValueTask.WhenAll(a, b) with two ValueTask<int> returns a tuple (int, int), while ValueTask<int>.WhenAll(a, b) returns int[].
Every supplied task is always awaited, even if an earlier one faulted or was canceled. If exactly one task fails, its original exception is rethrown. If two or more tasks fail, an AggregateException containing all exceptions in input order is thrown. As with Task.WhenAll, if all failed tasks were canceled, the first OperationCanceledException is rethrown instead. A single task that itself fails with an AggregateException is rethrown unchanged.
using NetEvolve.Extensions.Tasks;
try
{
await ValueTask.WhenAll(
DoSomethingAsync(),
DoSomethingElseAsync()
);
}
catch (AggregateException ex)
{
// Two or more operations failed, at least one of them with an error
foreach (var inner in ex.InnerExceptions)
{
Console.WriteLine(inner.Message);
}
}
catch (OperationCanceledException)
{
// All failed operations were canceled
Console.WriteLine("Operation was canceled");
}
catch (Exception ex)
{
// Exactly one operation failed
Console.WriteLine(ex.Message);
}Wait for an asynchronous operation, but no longer than the specified timeout. Task and ValueTask return true if the operation completes within the timeout, false otherwise. Task<T> and ValueTask<T> return a tuple (bool completedInTime, T result). The result is always delivered: if the timeout elapsed, the call still waits for the operation, then completedInTime is false and result holds its result.
Important
A timeout does not cancel the operation. For Task and ValueTask the call returns false and the operation keeps running in the background. For Task<T> and ValueTask<T> the call keeps waiting for the result. Pass a CancellationToken to the operation itself if it must be stopped.
using NetEvolve.Extensions.Tasks;
var task = SomeAsyncOperation();
var completed = await task.WithTimeoutAsync(5000); // 5 seconds timeout
if (completed)
{
Console.WriteLine("Operation completed successfully");
}
else
{
Console.WriteLine("Operation timed out");
}using NetEvolve.Extensions.Tasks;
var task = SomeAsyncOperation();
var completed = await task.WithTimeoutAsync(TimeSpan.FromSeconds(5));
if (completed)
{
Console.WriteLine("Operation completed successfully");
}
else
{
Console.WriteLine("Operation timed out");
}using NetEvolve.Extensions.Tasks;
var task = GetDataAsync();
var (completedInTime, result) = await task.WithTimeoutAsync(3000);
if (completedInTime)
{
Console.WriteLine($"Result: {result}");
}
else
{
// The operation took longer than the timeout, result is still available here
Console.WriteLine("Operation timed out");
}using NetEvolve.Extensions.Tasks;
ValueTask operation = PerformAsyncOperation();
var completed = await operation.WithTimeoutAsync(TimeSpan.FromSeconds(10));
if (!completed)
{
Console.WriteLine("Operation did not complete in time");
}using NetEvolve.Extensions.Tasks;
ValueTask<int> operation = GetValueAsync();
var (completedInTime, result) = await operation.WithTimeoutAsync(TimeSpan.FromSeconds(10));
if (completedInTime)
{
Console.WriteLine($"Result: {result}");
}using NetEvolve.Extensions.Tasks;
using var cts = new CancellationTokenSource();
var task = LongRunningOperation();
try
{
var completed = await task.WithTimeoutAsync(5000, cts.Token);
if (!completed)
{
Console.WriteLine("Timeout occurred");
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was cancelled");
}All extension methods are available for:
TaskTask<T>ValueTaskValueTask<T>
Creates a task that completes when all of the supplied ValueTask instances have completed.
The following behavior applies to all overloads:
- Every supplied task is awaited exactly once, even if an earlier one faulted or was canceled.
- Each supplied
ValueTaskis consumed byWhenAlland must not be awaited again by the caller. - An empty array, span or sequence completes synchronously. The generic overloads return an empty array.
- If exactly one task faulted or was canceled, its original exception is rethrown with the stack trace preserved. An
OperationCanceledExceptionstays anOperationCanceledException. - If two or more tasks failed and at least one of them faulted, an
AggregateExceptioncontaining all exceptions in input order is thrown. If all failed tasks were canceled, the firstOperationCanceledExceptionis rethrown, as withTask.WhenAll. - Arrays, spans and sequences are copied before the first await. Later changes by the caller have no effect.
Waits for all tasks in an enumerable collection to complete. The collection is enumerated exactly once.
Parameters:
tasks(IEnumerable<ValueTask>): The tasks to wait on for completion.
Returns: ValueTask - A task that represents the completion of all supplied tasks.
Exceptions:
ArgumentNullException: If the tasks argument is null.AggregateException: If two or more tasks faulted or were canceled.
Waits for all tasks in an array to complete.
Parameters:
tasks(ValueTask[]): The tasks to wait on for completion.
Returns: ValueTask - A task that represents the completion of all supplied tasks.
Exceptions:
ArgumentNullException: If the tasks argument is null.AggregateException: If two or more tasks faulted or were canceled.
Waits for all tasks in a span to complete. The span is copied before the first await.
Parameters:
tasks(ReadOnlySpan<ValueTask>): The tasks to wait on for completion.
Returns: ValueTask - A task that represents the completion of all supplied tasks.
Exceptions:
AggregateException: If two or more tasks faulted or were canceled.
Waits for all tasks in an enumerable collection to complete and returns their results. The collection is enumerated exactly once.
Parameters:
tasks(IEnumerable<ValueTask<TResult>>): The tasks to wait on for completion.
Returns: ValueTask<TResult[]> - A task containing an array of all task results in the same order as the input tasks.
Exceptions:
ArgumentNullException: If the tasks argument is null.AggregateException: If two or more tasks faulted or were canceled.
Waits for all tasks in an array to complete and returns their results.
Parameters:
tasks(ValueTask<TResult>[]): The tasks to wait on for completion.
Returns: ValueTask<TResult[]> - A task containing an array of all task results in the same order as the input tasks.
Exceptions:
ArgumentNullException: If the tasks argument is null.AggregateException: If two or more tasks faulted or were canceled.
Waits for all tasks in a span to complete and returns their results. The span is copied before the first await.
Parameters:
tasks(ReadOnlySpan<ValueTask<TResult>>): The tasks to wait on for completion.
Returns: ValueTask<TResult[]> - A task containing an array of all task results in the same order as the input tasks.
Exceptions:
AggregateException: If two or more tasks faulted or were canceled.
Waits for two or three tasks to complete. No array is allocated.
Parameters:
task1,task2,task3(ValueTask): The tasks to wait on for completion.
Returns: ValueTask - A task that represents the completion of all supplied tasks.
Exceptions:
AggregateException: If two or more tasks faulted or were canceled.
WhenAll<TResult>(ValueTask<TResult>, ValueTask<TResult>) and WhenAll<TResult>(ValueTask<TResult>, ValueTask<TResult>, ValueTask<TResult>)
Waits for two or three tasks of the same result type to complete and returns their results. No argument array is allocated. Called as ValueTask<TResult>.WhenAll(...).
Parameters:
task1,task2,task3(ValueTask<TResult>): The tasks to wait on for completion.
Returns: ValueTask<TResult[]> - A task containing an array of all task results in the same order as the input tasks.
Exceptions:
AggregateException: If two or more tasks faulted or were canceled.
Waits for two, three or four tasks with different result types to complete and returns their results as a tuple. Called as ValueTask.WhenAll(...).
Parameters:
task1totask4(ValueTask<T1> to ValueTask<T4>): The tasks to wait on for completion.
Returns: ValueTask<(T1, T2)>, ValueTask<(T1, T2, T3)> or ValueTask<(T1, T2, T3, T4)> - A task containing the results in the same order as the input tasks.
Exceptions:
AggregateException: If two or more tasks faulted or were canceled.
Note
ValueTask.WhenAll(a, b) with two ValueTask<int> binds to the tuple overload and returns (int, int). Use ValueTask<int>.WhenAll(a, b) to get int[].
The following behavior applies to all overloads:
- A timeout of zero waits for the task to complete and reports
false. - An infinite timeout waits for the task to complete and reports
true. - A task that is already completed reports
truewithout starting a timer. - If the timeout elapsed, the task is not canceled.
TaskandValueTaskreportfalseimmediately and the task keeps running in the background.Task<T>andValueTask<T>wait for the result and reportcompletedInTimeasfalse. - If the task faults or is canceled while waiting, its exception is rethrown. A
TaskorValueTaskthat has already faulted or been canceled when the call is made reportstruewithout rethrowing;Task<T>andValueTask<T>rethrow.
| Extended type | Return type |
|---|---|
Task |
Task<bool> |
Task<T> |
Task<(bool completedInTime, T result)> |
ValueTask |
ValueTask<bool> |
ValueTask<T> |
ValueTask<(bool completedInTime, T result)> |
Waits for a task to complete within the specified timeout in milliseconds.
Parameters:
timeoutInMilliseconds(int): Timeout in milliseconds. UseTimeout.Infinite(-1) to wait indefinitely.cancellationToken(CancellationToken): Optional cancellation token.
Returns: See the table above. true (or completedInTime is true and result is the result of the operation) if the operation completed within the timeout; otherwise false (or completedInTime is false and result is the result of the operation, delivered once it completed).
Exceptions:
ArgumentNullException: If the task is null (TaskandTask<T>only).ArgumentOutOfRangeException: If timeout is less than -1.OperationCanceledException: If the cancellation token is canceled before the task completed or the timeout elapsed.
Waits for a task to complete within the specified timeout.
Parameters:
timeout(TimeSpan): Timeout duration. UseTimeout.InfiniteTimeSpanto wait indefinitely.cancellationToken(CancellationToken): Optional cancellation token.
Returns: See the table above. true (or completedInTime is true and result is the result of the operation) if the operation completed within the timeout; otherwise false (or completedInTime is false and result is the result of the operation, delivered once it completed).
Exceptions:
ArgumentNullException: If the task is null (TaskandTask<T>only).ArgumentOutOfRangeException: If timeout is less thanTimeout.InfiniteTimeSpan.OperationCanceledException: If the cancellation token is canceled before the task completed or the timeout elapsed.
- Prefer WhenAll over sequential awaits: When you have multiple independent
ValueTaskoperations that are already started, useWhenAllto await them together. All of them are observed, even if one fails. - Result order is preserved: The results array maintains the same order as the input tasks, regardless of completion order.
- Handle exceptions: A single failure is rethrown as the original exception. Two or more failures are thrown as an
AggregateExceptionin input order. Catch both if you need to handle every failure. - Do not await the tasks again: Each
ValueTaskpassed toWhenAllis consumed. Awaiting it a second time is not supported.
- Check the return value:
completedInTimereports whether the operation finished within the timeout.resultis delivered either way. - Use TimeSpan for clarity: Prefer
TimeSpanoverloads for better readability in production code. - Handle cancellation: Consider using
CancellationTokenfor graceful shutdown scenarios. - Don't ignore timeouts: Log or handle timeout scenarios appropriately in your application.
- A timeout does not stop the operation:
TaskandValueTaskkeep running in the background,Task<T>andValueTask<T>are awaited until the result is there. Cancel the operation yourself if it must not continue.
- NetEvolve.Arguments - Argument validation library used internally
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
For issues, questions, or contributions, please visit the GitHub repository.