NetEvolve.Extensions.Tasks
3.0.0
Prefix Reserved
dotnet add package NetEvolve.Extensions.Tasks --version 3.0.0
NuGet\Install-Package NetEvolve.Extensions.Tasks -Version 3.0.0
<PackageReference Include="NetEvolve.Extensions.Tasks" Version="3.0.0" />
<PackageVersion Include="NetEvolve.Extensions.Tasks" Version="3.0.0" />
<PackageReference Include="NetEvolve.Extensions.Tasks" />
paket add NetEvolve.Extensions.Tasks --version 3.0.0
#r "nuget: NetEvolve.Extensions.Tasks, 3.0.0"
#:package NetEvolve.Extensions.Tasks@3.0.0
#addin nuget:?package=NetEvolve.Extensions.Tasks&version=3.0.0
#tool nuget:?package=NetEvolve.Extensions.Tasks&version=3.0.0
NetEvolve.Extensions.Tasks
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.
📦 Installation
dotnet add package NetEvolve.Extensions.Tasks
🎯 Features
- 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, .NET 10.0, and .NET 11.0
- Lightweight: Minimal dependencies, focused on essential functionality
- Modern: Supports both
TaskandValueTaskpatterns
🚀 Usage
WhenAll (ValueTask)
Aggregate multiple ValueTask operations, similar to Task.WhenAll. This is useful when you have multiple ValueTask instances that you want to await together.
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[].
ValueTask with params array
using NetEvolve.Extensions.Tasks;
await ValueTask.WhenAll(
DoSomethingAsync(),
DoSomethingElseAsync(),
DoAnotherThingAsync()
);
Console.WriteLine("All operations completed");
ValueTask with IEnumerable
using NetEvolve.Extensions.Tasks;
var tasks = new List<ValueTask>
{
ProcessItemAsync(1),
ProcessItemAsync(2),
ProcessItemAsync(3)
};
await ValueTask.WhenAll(tasks);
ValueTask<T> with results
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);
}
ValueTask<T> with IEnumerable
using NetEvolve.Extensions.Tasks;
IEnumerable<ValueTask<string>> tasks = GetTasksAsync();
string[] results = await ValueTask<string>.WhenAll(tasks);
Two or three tasks without an array
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));
Different result types (tuple)
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()
);
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[].
Exception handling
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);
}
WithTimeoutAsync
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.
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.
Task with Timeout (milliseconds)
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");
}
Task with Timeout (TimeSpan)
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");
}
Task<T> with Timeout
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");
}
ValueTask with Timeout
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");
}
ValueTask<T> with Timeout
using NetEvolve.Extensions.Tasks;
ValueTask<int> operation = GetValueAsync();
var (completedInTime, result) = await operation.WithTimeoutAsync(TimeSpan.FromSeconds(10));
if (completedInTime)
{
Console.WriteLine($"Result: {result}");
}
With CancellationToken
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");
}
📚 API Reference
Extension Methods
All extension methods are available for:
TaskTask<T>ValueTaskValueTask<T>
WhenAll
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.
WhenAll(IEnumerable<ValueTask>)
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.
WhenAll(params ValueTask[])
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.
WhenAll(ReadOnlySpan<ValueTask>) (.NET 9+)
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.
WhenAll<TResult>(IEnumerable<ValueTask<TResult>>)
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.
WhenAll<TResult>(params ValueTask<TResult>[])
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.
WhenAll<TResult>(ReadOnlySpan<ValueTask<TResult>>) (.NET 9+)
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.
WhenAll(ValueTask, ValueTask) and WhenAll(ValueTask, ValueTask, ValueTask)
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.
WhenAll<T1, T2>(ValueTask<T1>, ValueTask<T2>) up to WhenAll<T1, T2, T3, T4>(...)
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.
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[].
WithTimeoutAsync
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)> |
WithTimeoutAsync(int, CancellationToken)
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.
WithTimeoutAsync(TimeSpan, CancellationToken)
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.
WithTimeoutAsync(TimeSpan, TimeProvider, CancellationToken) (.NET 8+)
Same behavior as WithTimeoutAsync(TimeSpan, CancellationToken), but the timeout is measured by the supplied TimeProvider. Use it to test timeouts deterministically, for example with FakeTimeProvider.
var completed = await task.WithTimeoutAsync(TimeSpan.FromSeconds(5), timeProvider, cancellationToken);
Additional exceptions:
ArgumentNullException: IftimeProvideris null.
🎓 Best Practices
WhenAll
- 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.
WithTimeoutAsync
- 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.
🔗 Related Projects
- NetEvolve.Arguments - Argument validation library used internally
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📞 Support
For issues, questions, or contributions, please visit the GitHub repository.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- NetEvolve.Arguments (>= 4.0.0)
- System.Threading.Tasks.Extensions (>= 4.6.3)
-
net10.0
- NetEvolve.Arguments (>= 4.0.0)
-
net11.0
- NetEvolve.Arguments (>= 4.0.0)
-
net6.0
- NetEvolve.Arguments (>= 4.0.0)
-
net7.0
- NetEvolve.Arguments (>= 4.0.0)
-
net8.0
- NetEvolve.Arguments (>= 4.0.0)
-
net9.0
- NetEvolve.Arguments (>= 4.0.0)
NuGet packages (83)
Showing the top 5 NuGet packages that depend on NetEvolve.Extensions.Tasks:
| Package | Downloads |
|---|---|
|
NetEvolve.HealthChecks.SqlServer
Contains HealthChecks for Microsoft SqlServer, based on the nuget package `Microsoft.Data.SqlClient`. |
|
|
NetEvolve.HealthChecks.Abstractions
Contains abstract implementations for the `NetEvolve.HealthChecks`. |
|
|
NetEvolve.HealthChecks.Oracle
Contains HealthChecks for Oracle Databases, based on the nuget package `Oracle.ManagedDataAccess.Core`. |
|
|
NetEvolve.HealthChecks.Dapr
Contains HealthChecks for Dapr, based on the nuget package `Dapr.Client`. |
|
|
NetEvolve.HealthChecks.SqlServer.Legacy
Contains HealthChecks for Microsoft SqlServer, based on the nuget package `System.Data.SqlClient`. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.0.0 | 56 | 12/3/2026 |
| 2.1.515 | 286 | 11/8/2026 |
| 2.1.484 | 127 | 10/29/2026 |
| 2.1.357 | 8,201 | 8/23/2026 |
| 2.1.338 | 7,101 | 8/18/2026 |
| 2.1.283 | 11,143 | 7/23/2026 |
| 2.1.227 | 23,307 | 5/10/2026 |
| 2.1.147 | 8,390 | 3/23/2026 |
| 2.1.0 | 16,019 | 1/4/2026 |
| 2.0.90 | 247 | 1/3/2026 |
| 2.0.75 | 6,162 | 12/31/2025 |
| 2.0.46 | 8,573 | 12/11/2025 |
| 2.0.11 | 6,712 | 11/30/2025 |
| 2.0.8 | 2,271 | 11/28/2025 |
| 2.0.0 | 1,343 | 11/21/2025 |
| 1.3.74 | 24,528 | 5/4/2025 |
| 1.3.0 | 7,205 | 12/16/2024 |
| 1.2.188 | 1,527 | 11/29/2024 |
| 1.2.113 | 2,283 | 9/12/2024 |
| 1.2.98 | 1,760 | 8/26/2024 |