Skip to content

Feature request: Add overloads for CancellationToken.[Unsafe]Register that pass the CancellationToken to the registered function  #40475

@geoffkizer

Description

@geoffkizer

Background and Motivation

CancellationToken.Register and UnsafeRegister currently take callback arguments typed as either Action or Action<object> when used with user state.

It's very common for the registered callback to need to access the CancellationToken on which it is registered. For example, you often want to generate an OperationCanceledException with the original CancellationToken. Since the callback does not get passed this token, it needs to store it separately, often only for this specific purpose.

See for example: https://github.com/dotnet/runtime/blob/master/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/CreditWaiter.cs#L51

Proposed API

struct CancellationToken
{
    public CancellationTokenRegistration Register(Action<object?, CancellationToken> callback, object? state);
    public CancellationTokenRegistration UnsafeRegister(Action<object?, CancellationToken> callback, object? state);
}

Usage Examples

Considering the above example from CreditWaiter, this would allow the _cancellationToken field to be removed, and the code changed to the following:

    _registration = cancellationToken.UnsafeRegister(static (token, s) =>
    {
        var thisRef = (CreditWaiter)s!;
        thisRef._source.SetException(ExceptionDispatchInfo.SetCurrentStackTrace(new OperationCanceledException(token)));
    }, this);

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions