Async Concepts
Cancellation Signal
Use a cancellation flag to decide whether work should continue.
async
Long-running async work often receives a cancellation signal and checks it before starting the next step.
Cancellation Signal
CancellationSignal.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static void Main()
{
bool cancelRequested = false;
string nextStep = cancelRequested ? "stop" : "download";
string state = cancelRequested ? "cancelled" : "running";
Console.WriteLine($"cancelRequested={cancelRequested}");
Console.WriteLine($"nextStep={nextStep}");
Console.WriteLine($"state={state}");
}
}
using System;
class Program
{
static void Main()
{
bool cancelRequested = true;
string nextStep = cancelRequested ? "stop" : "download";
string state = cancelRequested ? "cancelled" : "running";
Console.WriteLine($"cancelRequested={cancelRequested}");
Console.WriteLine($"nextStep={nextStep}");
Console.WriteLine($"state={state}");
}
}
cancelRequested ← False, nextStep ← download, state ← running
4{5 static void Main()6 {7 bool cancelRequested→ False = false; //@cancelRequested=true, false8 string nextStep→ download = cancelRequestedFalse ? "stop" : "download";9 string state→ running = cancelRequestedFalse ? "cancelled" : "running";1011 Console.WriteLine($"cancelRequested={cancelRequestedFalse}");12 Console.WriteLine($"nextStep={nextStepdownload}");13 Console.WriteLine($"state={staterunning}");14 }outputcancelRequested=False nextStep=download state=running
cancelRequested ← True, nextStep ← stop, state ← cancelled
4{5 static void Main()6 {7 bool cancelRequested→ True = true;8 string nextStep→ stop = cancelRequestedTrue ? "stop" : "download";9 string state→ cancelled = cancelRequestedTrue ? "cancelled" : "running";1011 Console.WriteLine($"cancelRequested={cancelRequestedTrue}");12 Console.WriteLine($"nextStep={nextStepstop}");13 Console.WriteLine($"state={statecancelled}");14 }outputcancelRequested=True nextStep=stop state=cancelled
Follow the Signal
cancelRequestedstarts asfalse.- The
nextStepchoice checks that flag. - Because the flag is false,
nextStepbecomesdownload. - The
statechoice uses the same flag. - The program prints
cancelRequested=False,nextStep=download, andstate=running. | cancelRequested | nextStep | state | | --- | --- | --- | | False | download | running | | True | stop | cancelled |
Exercise: CancellationSignal.cs
Reproduce cancelRequested=False, nextStep=download, and state=running, then set cancelRequested to true and predict nextStep=stop and state=cancelled.