Skip to content

About

Extension methods for Task, Task<T>, ValueTask and ValueTask<T> to simplify asynchronous programming, including timeout support.

Topics

Resources

Code of conduct

Contributing

Stars

1 star

Watchers

4 watching

Forks

Latest commit

Β 

History

1,176 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

NetEvolve.Extensions.Tasks

NuGet License

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 ValueTask or ValueTask<T> operations similar to Task.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 Task and ValueTask patterns

πŸš€ 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.

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[].

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()
);

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[].

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.

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.

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:

  • Task
  • Task<T>
  • ValueTask
  • ValueTask<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 ValueTask is consumed by WhenAll and 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 OperationCanceledException stays an OperationCanceledException.
  • If two or more tasks failed and at least one of them faulted, an AggregateException containing all exceptions in input order is thrown. If all failed tasks were canceled, the first OperationCanceledException is rethrown, as with Task.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:

  • task1 to task4 (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[].

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 true without starting a timer.
  • If the timeout elapsed, the task is not canceled. Task and ValueTask report false immediately and the task keeps running in the background. Task<T> and ValueTask<T> wait for the result and report completedInTime as false.
  • If the task faults or is canceled while waiting, its exception is rethrown. A Task or ValueTask that has already faulted or been canceled when the call is made reports true without rethrowing; Task<T> and ValueTask<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. Use Timeout.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 (Task and Task<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. Use Timeout.InfiniteTimeSpan 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 (Task and Task<T> only).
  • ArgumentOutOfRangeException: If timeout is less than Timeout.InfiniteTimeSpan.
  • OperationCanceledException: If the cancellation token is canceled before the task completed or the timeout elapsed.

πŸŽ“ Best Practices

WhenAll

  1. Prefer WhenAll over sequential awaits: When you have multiple independent ValueTask operations that are already started, use WhenAll to await them together. All of them are observed, even if one fails.
  2. Result order is preserved: The results array maintains the same order as the input tasks, regardless of completion order.
  3. Handle exceptions: A single failure is rethrown as the original exception. Two or more failures are thrown as an AggregateException in input order. Catch both if you need to handle every failure.
  4. Do not await the tasks again: Each ValueTask passed to WhenAll is consumed. Awaiting it a second time is not supported.

WithTimeoutAsync

  1. Check the return value: completedInTime reports whether the operation finished within the timeout. result is delivered either way.
  2. Use TimeSpan for clarity: Prefer TimeSpan overloads for better readability in production code.
  3. Handle cancellation: Consider using CancellationToken for graceful shutdown scenarios.
  4. Don't ignore timeouts: Log or handle timeout scenarios appropriately in your application.
  5. A timeout does not stop the operation: Task and ValueTask keep running in the background, Task<T> and ValueTask<T> are awaited until the result is there. Cancel the operation yourself if it must not continue.

πŸ”— Related Projects

πŸ“„ 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.

About

Extension methods for Task, Task<T>, ValueTask and ValueTask<T> to simplify asynchronous programming, including timeout support.

Topics

Resources

Code of conduct

Contributing

Stars

1 star

Watchers

4 watching

Forks

Releases

Sponsor this project

Used by

Contributors

Languages