In C#, how do you give each imported file a 30-second limit while honouring the user's Cancel button, and tell the two apart?
answer
- a second source just for time
- CancelAfter or the TimeSpan constructor
- one token that fires for either
- ask the sources, not the exception
basics
~10 sCreate a per-file CancellationTokenSource with a 30-second delay, combine it with the user's token through CancellationTokenSource.CreateLinkedTokenSource, and pass the linked token down. Afterwards, check which source has IsCancellationRequested set.
solid answer
~40 sFor each file, create `using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));` (or call `CancelAfter` on a source you own), then `using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(userToken, timeoutCts.Token);` and pass `linkedCts.Token` to the file's work. The linked source is cancelled as soon as either input is. When an `OperationCanceledException` arrives, ask the sources what happened: if `timeoutCts.IsCancellationRequested` is true and `userToken.IsCancellationRequested` is false, the file ran out of time, which you can turn into a `TimeoutException` or a per-file error; otherwise the user cancelled and the exception should propagate. Do not compare `ex.CancellationToken` with the user's token: the exception carries the linked token. Dispose both sources when the file is done.
code
csharp · 27 linesusing var userCts = new CancellationTokenSource(); // wired to the Cancel button
Console.WriteLine(await ImportFileAsync("small.csv", 50, userCts.Token));
try { await ImportFileAsync("huge.csv", 5000, userCts.Token); }
catch (TimeoutException ex) { Console.WriteLine(ex.Message); }
userCts.CancelAfter(50); // simulate a click on Cancel 50 ms from now
try { await ImportFileAsync("huge.csv", 5000, userCts.Token); }
catch (OperationCanceledException ex)
{
Console.WriteLine($"Cancelled by the user; ex.CancellationToken is the user's token: {ex.CancellationToken == userCts.Token}");
}
static async Task<string> ImportFileAsync(string file, int workMs, CancellationToken userToken)
{
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); // 30 s in production
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(userToken, timeoutCts.Token);
try
{
await Task.Delay(workMs, linkedCts.Token); // stands in for parsing and saving
return $"{file}: imported";
}
catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested && !userToken.IsCancellationRequested)
{
throw new TimeoutException($"{file}: exceeded the per-file limit");
}
}go deeper
Recall that a CancellationTokenSource can cancel itself after a delay, and that CreateLinkedTokenSource combines tokens.
Walk through the per-file linked source, explain why the exception carries the linked token, and show how to tell a timeout from a user cancel.
Cover disposal of linked and timed sources in a long batch, the near-simultaneous race, and what happens when the work cannot accept a token.
Decide where deadlines are set in a layered codebase, who owns each source, and how timeouts are reported differently from user cancellations.
## The goal The import job has two independent reasons to stop working on a file: - the **user** clicks Cancel, which should stop the whole import; - the **file** has been running for more than 30 seconds, which should fail that one file and let the import move on. The file's work wants one `CancellationToken` to forward to its I/O calls. The answer is to build one token that fires for either reason, and to keep the two original signals around so you can tell afterwards which one it was. ## Making a timeout A `CancellationTokenSource` can cancel itself after a delay in two ways: | API | When the countdown starts | Notes | |---|---|---| | `new CancellationTokenSource(TimeSpan delay)` (or the `int millisecondsDelay` overload) | at construction | a fresh source dedicated to the deadline | | `cts.CancelAfter(TimeSpan delay)` (or `int millisecondsDelay`) | at the call | each later call **resets** the delay if the source is not cancelled yet; does nothing once it is | Both throw `ArgumentOutOfRangeException` for a delay below -1 ms or above the timer's maximum, and `CancelAfter` throws `ObjectDisposedException` on a disposed source. A source with a pending delay holds a timer, which is one more reason to dispose it when the file is done: disposing stops the timer. A test can drive the delay without waiting by passing a `TimeProvider` to the `CancellationTokenSource(TimeSpan, TimeProvider)` constructor; time abstractions themselves are covered with the base class library. ## Linking the two `CancellationTokenSource.CreateLinkedTokenSource` returns a **new source that is cancelled when any of its input tokens is cancelled**. It has overloads for one token, two tokens, and any number of them. The new source can also be cancelled directly, and its own cancellation does not flow back to the inputs. Per file, the steps are: 1. `using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));` 2. `using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(userToken, timeoutCts.Token);` 3. Pass `linkedCts.Token`, and only that token, to the parsing and saving calls. 4. Catch `OperationCanceledException` and decide what it means. The `using` declarations matter. The linked source subscribes to each input token, so until it is disposed it stays registered with the user's source, which lives for the whole import. A thousand files would otherwise leave a thousand stale registrations behind. ## Telling user cancel from timeout The exception does not say why it was thrown. Its `CancellationToken` property holds whatever token the throwing code observed, which here is the **linked** token, so `ex.CancellationToken == userToken` is `false` even when the user cancelled. Ask the sources instead: - `userToken.IsCancellationRequested` true: the user cancelled. Let the exception propagate so the whole import stops. - `timeoutCts.IsCancellationRequested` true and the user's token not cancelled: the file timed out. Turn it into a `TimeoutException` or a per-file failure and continue with the next file. - Neither: something else cancelled, such as a library's internal timeout. Treat it as an ordinary failure. An exception filter keeps this compact: `catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested && !userToken.IsCancellationRequested)`. Checking the user's token too covers the race in which both fire at nearly the same moment: this filter then treats it as a user cancel, which stops the import as the user asked. ## Things that go wrong - **One shared timeout source for the whole batch.** A single `CancelAfter(30 s)` set once limits the entire import to 30 seconds, not each file. Create the timeout per file, or call `CancelAfter` again on a per-file source. - **Linking but passing the wrong token.** Passing `userToken` instead of `linkedCts.Token` to the work silently disables the timeout. - **Disposing the caller's source.** The import owns `timeoutCts` and `linkedCts` and disposes them; it must never dispose the source behind `userToken`. - **A timeout without a token.** If the parser does not accept a token, linking does nothing for it; that case is about abandoning the wait, not cancelling the work. ## Where this leaf stops Racing a task against `Task.Delay` with `Task.WhenAny` is the combinators' approach to a deadline and is covered there; deadlines a web host imposes on a request are covered with ASP.NET Core.
- In C#, what happens if you call CancelAfter twice on the same CancellationTokenSource?If the source has not been cancelled yet, the second call replaces the pending delay, and the countdown restarts from the second call. That makes `CancelAfter` usable as an idle timeout: call it again each time progress is made. Once the source is cancelled, further calls do nothing, and on a disposed source `CancelAfter` throws `ObjectDisposedException`.
- In C#, can cancelling a linked CancellationTokenSource cancel the user's token it was created from?No. Linking is one way: the linked source registers callbacks on its input tokens and cancels itself when any of them fires. Calling `Cancel()` on the linked source, or its own timeout firing, cancels only the linked source and its token, so the rest of the import keeps running with the user's token intact.
- In C#, why should a per-file linked CancellationTokenSource be disposed even when the file imports successfully?The linked source registered a callback on the user's token, and that registration lives as long as the user's source does, which is the whole import. Disposing the linked source removes the registration and stops any pending timer. Without it, every file leaves a registration and an object graph reachable from the long-lived source.
- Compares ex.CancellationToken with the user's token to detect a user cancel when the work used a linked token
- Sets one CancelAfter for the whole batch and believes each file gets 30 seconds
- Links the tokens but still passes the user's token to the file's work
- Disposes the CancellationTokenSource that belongs to the caller
- Believes cancelling the linked source also cancels its input tokens