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

cancelRequested
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}");
    }
}
  1. 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
  1. 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

  1. cancelRequested starts as false.
  2. The nextStep choice checks that flag.
  3. Because the flag is false, nextStep becomes download.
  4. The state choice uses the same flag.
  5. The program prints cancelRequested=False, nextStep=download, and state=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.