C#
ContinueWith
Learn to chain after a task with ContinueWith.
What is ContinueWith?
ContinueWith registers a continuation that runs when a Task completes. Example: task.ContinueWith(t => Next());. When the first task finishes, Next is called. This is the older way to build task chains.
In modern C#, await is usually more readable. Still, ContinueWith is useful for multi-step chains or fire-and-forget scenarios. The previous task is passed to the continuation as t.
ContinueWith vs await
ContinueWith and await do similar things but in different ways. await gives a natural, linear flow; the compiler builds the continuation automatically. ContinueWith requires you to write a lambda explicitly.
await captures the context (by default); ContinueWith does not. That is why library code often pairs ContinueWith with TaskScheduler.Default. For new code, prefer await.
Exercise Chain with ContinueWith
Define static Task<int> FirstStep() (return Task.FromResult(10);). Make Main a static async Task Main. Await the continuation with int doubled = await FirstStep().ContinueWith(prev => prev.Result * 2); and print with Console.WriteLine(doubled);.
Show example solution
In FirstStep body write return Task.FromResult(10);. Make Main static async Task Main() and write int doubled = await FirstStep().ContinueWith(prev => prev.Result * 2); Console.WriteLine(doubled);
Example solution:
using System;
using System.Threading.Tasks;
class Program
{
static Task<int> FirstStep()
{
return Task.FromResult(10);
}
static async Task Main()
{
int doubled = await FirstStep().ContinueWith(prev => prev.Result * 2);
Console.WriteLine(doubled);
}
}
Test yourself
-
Complete the ContinueWith call
task.____(t => Next());
Show answer
task.ContinueWith(t => Next());
-
Match the concepts
- ContinueWith
- Registers a continuation
- await
- Gives a natural flow
- TaskScheduler.Default
- Pool scheduler
- t => Next()
- Continuation lambda
-
When is ContinueWith useful?
- Instead of every async call
- Instead of async void
- Instead of Thread.Abort
- In multi-step chains or fire-and-forget scenarios
Show answer
In multi-step chains or fire-and-forget scenarios — Correct. ContinueWith is useful for chains and fire-and-forget.
Next lesson: Task.WhenAll