Parallelism and cancellation
Parallelism and cancellation
Concurrency means multiple operations may be in progress, while parallelism means work executes simultaneously. Parallel.For and Parallel.ForEach are useful for independent CPU-bound iterations. MaxDegreeOfParallelism limits concurrency but is not a promise of that many threads or a guarantee of speedup. Cancellation is cooperative: request it, pass the token to the operation, and decide how to handle partial work. Bound concurrent asynchronous operations separately, for example with SemaphoreSlim or Parallel.ForEachAsync.
Baseline: .NET 10 / C# 14; inherited SDK candidate 10.0.404. Each example is an independent console project. Outputs are reasoned, not executed. The native-library example is Linux-only and requires the included C source.
Compute independent results with bounded parallelism
Each iteration owns its output slot. Only read the array after the synchronous loop returns. Work order is irrelevant.
using System;using System.Threading.Tasks;int[] input = { 2, 4, 6, 8 };int[] output = new int[input.Length];Parallel.For(0, input.Length, new ParallelOptions { MaxDegreeOfParallelism = 2 }, i => output[i] = input[i] * input[i]);Console.WriteLine(string.Join(",", output));The index preserves result order even though scheduling order is unspecified. The loop completes before output is printed. Small jobs may be slower in parallel because of overhead.
Expected observation (reasoned, not executed):
4,16,36,64Handle a cancellation request before starting
Use a pre-canceled token for a deterministic case. With this ParallelOptions token, the loop reports cancellation through OperationCanceledException.
using System;using System.Threading;using System.Threading.Tasks;using var stop = new CancellationTokenSource();stop.Cancel();int completed = 0;try{ Parallel.For(0, 4, new ParallelOptions { MaxDegreeOfParallelism = 2, CancellationToken = stop.Token }, _ => Interlocked.Increment(ref completed));}catch (OperationCanceledException) when (stop.IsCancellationRequested){ Console.WriteLine("canceled");}Console.WriteLine(completed);A pre-canceled token avoids timing-dependent partial progress. Cancellation during a real loop can leave completed side effects; design idempotent work, checkpoints or compensation as needed.
Expected observation (reasoned, not executed):
canceled0Bound asynchronous access with permits
SemaphoreSlim can guard a limited-capacity resource across awaits. This controlled test takes the only permit, confirms another immediate attempt fails, then returns the permit.
using System;using System.Threading;using System.Threading.Tasks;using var permits = new SemaphoreSlim(1, 1);await permits.WaitAsync();try{ Console.WriteLine(await permits.WaitAsync(0));}finally{ permits.Release();}Console.WriteLine(await permits.WaitAsync(0));permits.Release();A zero-timeout wait reports whether a permit was acquired. Release only after a successful acquisition. A real async operation should pass its cancellation token to WaitAsync, use try/finally around the awaited work, and dispose the semaphore only after all users finish.
Expected observation (reasoned, not executed):
FalseTrueCommon mistakes and design trade-offs
Do not write a Parallel.For body as an async lambda: an Action-shaped overload cannot await its asynchronous completion. Use a suitable async API such as Parallel.ForEachAsync with explicit options. Bound the total number of queued tasks as well as active permits for large inputs; channels will cover backpressure next. Do not hold an ordinary lock across await or block a worker waiting for another iteration. Parallel loops may aggregate worker exceptions; cancellation does not roll back side effects.
Apply the concept
Plan a finite batch of four image-size calculations with concurrency at most two and stable output order. Explain how a cancellation after two completed jobs affects reporting, and how an async upload version should manage permits.
Check your work: Use Parallel.For with MaxDegreeOfParallelism=2 and distinct indexed slots for CPU work. After cancellation report only confirmed completed items; do not assume others rolled back. For async work use cancellation-aware SemaphoreSlim or Parallel.ForEachAsync with a finite input and release only acquired permits.
Continue with the next planned lesson in this track. For authoritative details, consult the linked source evidence and the reference drafts. All examples remain pending compiler and runtime verification.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Parallelism and cancellation — knowledge check
Apply the lesson concepts to the following scenarios.
What does MaxDegreeOfParallelism=2 guarantee?
How can output order remain stable?
Does cancellation undo completed writes?
When should SemaphoreSlim.Release be called?
Which is appropriate for an awaited async loop body?