Ferrous API Reference

All Types / Ferrous.Concurrency

class TaskScope [MustUse]

public sealed class TaskScope : IAsyncDisposable

A structured concurrency nursery inspired by Rust's std::thread::scope and tokio::task::JoinSet. Guarantees that every child task spawned inside the scope either completes or is cooperatively cancelled and awaited before leaving the await using block—preventing orphaned background tasks and unobserved exceptions. Compiled with .NET 11 runtime async (runtime-async=on) on net11.0.

Constructors

public TaskScope(CancellationToken cancellationToken = default)

Initializes a new TaskScope optionally linked to a parent cancellationToken.

Parameters
cancellationToken
An optional parent token whose cancellation propagates to all child tasks.

Properties

public CancellationToken Token

Gets the cooperative CancellationToken shared by all child tasks in this scope. Cancelled automatically when the parent token cancels, when any sibling task faults, when Cancel is called, or when the scope exits early.

Methods

public static async Task RunAsync(Func<TaskScope, Task> body, CancellationToken cancellationToken = default)

Creates a new TaskScope and executes body within it, awaiting all spawned tasks (or cancelling and draining them on failure) before returning.

Parameters
body
The async delegate that spawns child work on the scope.
cancellationToken
An optional parent cancellation token.

Returns: A task that completes when body and all spawned child tasks have finished.

public Task Spawn(Func<CancellationToken, Task> work)

Spawns a child task tracked by this scope. If the child throws a non-cancellation exception, all sibling tasks in the scope are immediately signalled via Token.

Parameters
work
The asynchronous work delegate receiving the scope's Token.

Returns: The tracked Task representing the child operation.

Exceptions
ObjectDisposedException
Thrown if the scope has already been disposed.
public Task<T> Spawn<T>(Func<CancellationToken, Task<T>> work)

Spawns a result-producing child task tracked by this scope. If the child throws a non-cancellation exception, all sibling tasks in the scope are immediately signalled via Token.

Type Parameters
T
The result type produced by the child task.
Parameters
work
The asynchronous work delegate receiving the scope's Token.

Returns: The tracked Task<TResult> representing the child operation.

Exceptions
ObjectDisposedException
Thrown if the scope has already been disposed.
public void Cancel()

Cooperatively cancels all tasks running inside this scope.

public async ValueTask WaitAllAsync()

Awaits all tasks spawned in this scope (including tasks spawned dynamically by children) and rethrows the first non-cancellation failure if any child faulted.

public async ValueTask DisposeAsync()

Cancels any still-running tasks (if WaitAllAsync was not called), awaits all spawned tasks so none leak past the scope boundary, and disposes resources.