-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Threading.Tasks
Milestone
Description
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.
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);AArnott and KalleOlaviNiemitalo
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Threading.Tasks