Completion and shutdown
Completion and shutdown
A graceful shutdown stops accepting new work, marks the input complete, and gives accepted work a chance to drain. An abort instead cancels active operations and may leave accepted work unfinished. Decide which behavior is required before writing cancellation logic. Channel completion is a terminal signal owned by the producer coordinator; cancellation tokens are cooperative requests, not forced interruption. Observe every task and record whether a shutdown is normal, canceled, or faulted.
Baseline: .NET 10 / C# 14 (SDK candidate inherited, not installed). Each example is an independent project with predicted output. Build and runtime verification are pending. Run only a reviewed fixture in an approved disposable environment.
Drain accepted work on normal completion
Submit finite work, then close the writer before consuming. This fixture has enough capacity for all items.
using System;using System.Threading.Channels;var queue = Channel.CreateBounded<string>(2);await queue.Writer.WriteAsync("A");await queue.Writer.WriteAsync("B");Console.WriteLine(queue.Writer.TryComplete());Console.WriteLine(queue.Writer.TryWrite("C"));await foreach (string item in queue.Reader.ReadAllAsync()) Console.WriteLine(item);await queue.Reader.Completion;Console.WriteLine("drained");Completion is not cancellation; both accepted entries survive.
Expected observation (reasoned, not executed):
TrueFalseABdrainedPropagate a producer failure
A failed producer signals the error instead of leaving consumers waiting forever. Await the completion task after draining the accepted prefix.
using System;using System.Threading.Channels;var queue = Channel.CreateBounded<int>(2);await queue.Writer.WriteAsync(4);queue.Writer.TryComplete(new InvalidOperationException("source failed"));Console.WriteLine(await queue.Reader.ReadAsync());try { await queue.Reader.Completion; }catch (InvalidOperationException error) { Console.WriteLine(error.Message); }The already buffered item can be read; completion then reports the original fault.
Expected observation (reasoned, not executed):
4source failedCancel a blocked producer when the consumer stops
A capacity-one queue contains one accepted item. A blocked second write is canceled deliberately, not by a timing-sensitive sleep.
using System;using System.Threading;using System.Threading.Channels;var queue = Channel.CreateBounded<int>(1);using var stop = new CancellationTokenSource();await queue.Writer.WriteAsync(1);var blocked = queue.Writer.WriteAsync(2, stop.Token);stop.Cancel();try { await blocked; }catch (OperationCanceledException) { Console.WriteLine("write canceled"); }finally { queue.Writer.TryComplete(); }await foreach (int item in queue.Reader.ReadAllAsync()) Console.WriteLine(item);Canceling the pending write does not revoke the previous accepted entry. A real abort can choose not to drain, but should account for unfinished work.
Expected observation (reasoned, not executed):
write canceled1Common mistakes and design limits
With multiple producers, a coordinator should complete only after all producers finish; individual producers must not close a shared writer prematurely. If any worker fails, cancel a shared token before awaiting all remaining tasks so blocked operations can exit. Awaiting WhenAll alone does not cancel peers. For a drain-first policy use separate stop-accepting and abort tokens; impose a deadline and document what happens to remaining jobs. In-memory channels do not provide durable delivery, exactly-once processing, or recovery after a crash.
Apply the concept
A producer submits jobs A and B; a consumer fails processing A while a third write is waiting. Design an abort policy and distinguish the status of A, B and the pending write.
Check your work: Cancel the shared token, signal writer termination, and observe producer and consumer failures. A failed; B was accepted but not necessarily processed; the waiting write may be canceled or may have won a race, so record actual acceptance. Recover from durable storage if the domain requires it.
Further study
Continue with the next planned lesson. Consult the official documentation for API contracts: channels, fullmode, channelcompletion. API and runtime verification remain incomplete.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Completion and shutdown — knowledge check
Apply the lesson concepts to the following scenarios.
Who should normally complete a shared writer?
What happens to accepted entries after normal completion?
Does Task.WhenAll cancel sibling tasks on failure?
Why use separate drain and abort policies?
Can an in-memory channel guarantee recovery after a process crash?