2

I am writing some internal framework code and at some point I want to throw an MyCustomException when TaskCanceledException happens, because I want to add the delay configured for the CancellationToken to the message. That is, in:

var cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(cancellationTokenDelay); return cancellationTokenSource.Token; 

I want to get the value passed to the CancelAfter method. The problem is: CancellationToken does not seem to expose this information. Is there any trick to get it?

(I already considered timing the operation with a Stopwatch, but I am looking for a more elegant alternative).

1 Answer 1

4

Not all CancellationToken's have a delay at all. It's quite common to use them with a CancellationTokenSource that calls cancel based on something other than a set amount of time passing.

You'll either need to pass along that information with the Cancellation token to the task, or create your own subclass of CancellationToken that is only used in conjunction with a delay and that exposes that information publicly.

Sign up to request clarification or add additional context in comments.

1 Comment

CancellationToken is a struct, so you can't subclass it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.