Skip to content

Continuations After Success

Question

When using ContinueWith, can you choose to run your continuation only when task has completed successfully?

Short interview answer

Yes. ContinueWith accepts continuation options such as OnlyOnRanToCompletion, but await with normal control flow is usually clearer for application code: code after a successful await runs only if the awaited task completed successfully.

Detailed answer

task.ContinueWith(next, TaskContinuationOptions.OnlyOnRanToCompletion) schedules next only for successful completion. A continuation is not the same as an exception-safe sequential workflow: it needs deliberate handling for cancellation, faults, scheduling, and its returned task. In most ordinary asynchronous methods, write await task; followed by the successful next step; a fault propagates at the await, and cancellation is also observable there. Use continuation APIs where their lower-level scheduling or composition semantics are specifically needed.

For example, task.ContinueWith(next, TaskContinuationOptions.OnlyOnRanToCompletion) does not run next after a fault or cancellation. In most application code, await task; await next(); makes the same success-only flow clearer.

Sources