How to implement sliding expiration for CancellationTokenSource i.e. to be able to reset its timeout interval?
TaskCompletionSource<T> source = new TaskCompletionSource<T>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(timeoutMs);
cancellationTokenSource.Token.Register(() => source.TrySetCanceled(), useSynchronizationContext: false);
// do work and eventually call source.TrySetResult()
// what is the right way to prolong CancellationTokenSource timeout?
return source.Task;
Some extra context:
Imagine application sending command and waiting for reply to arrive. Reply may take 0.1 or 10 seconds and may interrupt. If there is no new data for 1 second it is safe to timeout.
So setting fixed timeout exceeding 10 seconds seems a lot, but sling expiration fits perfectly: when new portion of data arrives, reset 1 second interval.
UPD
Why not to make timer myself. Of course that was my first thought. However looking into CancellationTokenSource source code (CTS is build on timer which is sealed and internal) got me thinking there is a reason for that and maybe I'm missing something.