Question

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).

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top