skip to content

A C# import wraps a parser that takes no CancellationToken in parseTask.WaitAsync(TimeSpan.FromSeconds(30)); why do slow files keep writing rows after the timeout fires?

level: seniorimportance: should knowfreq 42%

answer

  1. the wait ends, not the work
  2. a new task around the old one
  3. TimeoutException on the wrapper only
  4. the parser must take a token

basics

~10 s

Task.WaitAsync times out only the wait: it returns a new task that faults with TimeoutException, while the original parse task keeps running. Cancellation is cooperative, so stopping the parser needs a token it checks.

solid answer

~40 s

`Task.WaitAsync(TimeSpan)` returns a **separate** task (unless the original has already finished) that completes when the original does or faults with `TimeoutException` when the time is up; `WaitAsync(CancellationToken)` does the same with a cancelled outcome. Neither touches the original task, because a `Task` has no way to stop the code behind it. The parser therefore keeps parsing and writing rows after the import has moved on, and any exception it throws later goes unobserved unless something still awaits it. The fix is to make the parser cancellable: give it a `CancellationToken` parameter, forward the token to its I/O calls, call `ThrowIfCancellationRequested()` before each write, and pass it a token from a source with a 30-second delay. `WaitAsync` remains the right tool only for work you cannot change and can afford to abandon.

code

csharp · 23 lines
csharp
int rows = 0;

Task parse = ParseFileAsync();   // takes no CancellationToken
try
{
    await parse.WaitAsync(TimeSpan.FromMilliseconds(120));   // 30 s in production
}
catch (TimeoutException)
{
    Console.WriteLine($"WaitAsync timed out; rows written so far: {rows}");
}

await Task.Delay(500);
Console.WriteLine($"Half a second later: parse is {parse.Status}, rows written: {rows}");

async Task ParseFileAsync()
{
    for (int i = 0; i < 10; i++)
    {
        await Task.Delay(50);   // stands in for parsing one batch
        rows++;                 // and writing it
    }
}

go deeper

for a junior

Recall that a Task has no way to stop the code behind it, and that WaitAsync only stops waiting.

for a middle

Explain the three ways the task returned by WaitAsync completes, and what the original task does in each case.

for a senior

Diagnose piled-up abandoned work from symptoms, make the parser cooperative with forwarded tokens and checkpoints, and decide when abandoning is acceptable.

for a principal

Set the expectation that every long-running internal API accepts a token, and decide how abandoned third-party work is tracked and contained.

## What WaitAsync actually does `Task.WaitAsync` (with matching overloads on `Task<TResult>`) has overloads taking a `CancellationToken`, a `TimeSpan`, both, and versions with a `TimeProvider`. When the original task is still running, each returns a **new task** that completes in one of three ways: | What happens first | The returned task | |---|---| | the original task completes | completes the same way: result, exception or cancellation | | the timeout elapses | faults with `TimeoutException` | | the token is cancelled | ends `Canceled`; awaiting it throws `TaskCanceledException` | The original task is not modified. A `Task` is a promise of a result, not a handle to a thread: it has no `Cancel` or `Abort` method, and .NET has no supported way to forcibly stop managed code from the outside (`Thread.Abort` throws `PlatformNotSupportedException` on every .NET release since .NET Core). So when `WaitAsync` gives up, **the work it was waiting for continues**: the parser keeps reading, keeps writing rows, and finishes or fails later with nobody listening. ## Why the rows keep growing In the import, `ParseFileAsync()` takes no token. The caller writes: 1. `Task parse = ParseFileAsync();` starts the work. 2. `await parse.WaitAsync(TimeSpan.FromSeconds(30));` waits at most 30 seconds. 3. On timeout, the caller catches `TimeoutException`, marks the file as failed and moves on to the next file. 4. Meanwhile `parse` is still running, so the "failed" file keeps writing rows, and the next file's parse now runs alongside it. Repeated over a large batch, this piles up abandoned parsers that compete for the same database and disk, which looks like the import getting slower and slower and produces duplicate or half-written data. If an abandoned parser later throws, its exception lands on a task nobody awaits; how such unobserved exceptions surface is covered with task combinators. ## The fix: make the work cooperative Cancellation in .NET is **cooperative**: the code doing the work has to observe a token. So the real fix is in the parser, not around it. - Give it a parameter: `ParseFileAsync(string path, CancellationToken cancellationToken)`. - **Forward** the token to every awaited call that accepts one: stream reads, database calls, `Task.Delay`. - Add **checkpoints**: `cancellationToken.ThrowIfCancellationRequested()` before each batch write, and every so often in a CPU-bound loop. - Give each file a token with a deadline: `using var perFileCts = new CancellationTokenSource(TimeSpan.FromSeconds(30));` and pass `perFileCts.Token`. Now, when the deadline passes, the parser's next I/O call or checkpoint throws `OperationCanceledException`, its `finally` blocks run, and by the time the caller sees the exception the work has actually stopped. How quickly it stops depends on how often it checks: a parser that checks between 1,000-row batches stops within one batch. ## When WaitAsync is still the right tool Some work cannot be cancelled: a third-party method with no token parameter, or a legacy synchronous call wrapped in `Task.Run`. Then the choice is to wait for it or to **abandon the wait**: - Use `WaitAsync` when stopping the wait is enough, for example to keep a progress screen responsive, and the work's side effects are harmless if it finishes late. - Keep a reference to the abandoned task if its outcome still matters, and observe its result or exception later. - Do not start a replacement for the same file while the abandoned one may still be writing. - Prefer fixing the API: adding a `CancellationToken` parameter to an internal method is usually cheaper than managing abandoned work. ## Related pitfalls - Passing a token to `Task.Run(work, token)` only prevents the delegate from **starting** if the token is cancelled before it begins; once the delegate runs, it stops only if it checks the token itself. - `WaitAsync(CancellationToken.None)` and `WaitAsync(Timeout.InfiniteTimeSpan)` return the original task itself, as does any overload on a task that has already completed; there is nothing to give up on. - Racing a task against `Task.Delay` with `Task.WhenAny` has exactly the same limitation as `WaitAsync`: the loser keeps running. That combinator approach is covered with task combinators.

  • In C#, what does awaiting task.WaitAsync(token) throw when the token is cancelled before the task completes?
    A `TaskCanceledException`, which derives from `OperationCanceledException`, because the task `WaitAsync` returned ends `Canceled`. The original task is unaffected and may still complete successfully later; only the wait was cancelled. With the `TimeSpan` overloads the returned task instead faults with `TimeoutException`.
  • In C#, how quickly does a cooperative parser stop after its CancellationToken is cancelled?
    Only as quickly as it next observes the token: an awaited I/O call that was given the token typically completes as cancelled right away, while CPU-bound code stops at its next `ThrowIfCancellationRequested()` call. If a batch takes ten seconds between checks, cancellation can take up to ten seconds. The interval between checkpoints is the latency you are choosing.

  • Believes WaitAsync with a timeout stops the task it wraps
  • Thinks passing a token to Task.Run lets the runtime stop the delegate mid-run
  • Retries the same file at once while the abandoned parse may still be writing
  • Assumes the abandoned task's later exception will surface somewhere on its own
  • Expects a Task object to offer a Cancel or Abort method