C# / Advanced: Lifetimes, Concurrency, and Runtime Design / Lesson 21
Bounded channels and completion
Coordinate bounded .NET channels, cancellation, and completion.
On this page
Lesson goals
- Choose a bounded channel policy.
- Test completion and cancellation.
- Trace full-mode item outcomes and distinguish queue bounds from total resource limits.
- Coordinate producer completion, cancellation and consumer draining.
Define a bounded pipeline
A bounded channel connects producers and consumers while limiting queued items. Its capacity and full-mode policy determine whether a producer waits or items are dropped. Define who owns completion, how failures and cancellation propagate, and whether every item must be processed. A capacity limit bounds queued items, not necessarily all memory used by producers, consumers, or the items themselves.
Choose the full policy
With the default Wait full mode, TryWrite returns false immediately when the channel is full, while WriteAsync can wait for space. The example creates capacity one and performs two nonblocking writes; the second cannot fit. Choose a drop policy only when losing the relevant item is acceptable and observable in the application contract. Do not assume every successful write implies immediate processing.
using System;
using System.Threading.Channels;
public class Program
{
public static void Main()
{
var channel = Channel.CreateBounded<int>(1);
Console.WriteLine($"{channel.Writer.TryWrite(1)} {channel.Writer.TryWrite(2)}");
}
}
True False
The second nonblocking write finds the channel full.
Complete the channel
The writer completes a channel when no more items will be written. A reader can consume the remaining items and then observe completion. The example writes one value, completes the writer, and asynchronously enumerates the reader. In a multi-producer design, coordinate completion only after all producers finish; closing while another producer can still write creates a failure path.
using System;
using System.Threading.Channels;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
var channel = Channel.CreateBounded<int>(1);
await channel.Writer.WriteAsync(7);
channel.Writer.Complete();
await foreach (int value in channel.Reader.ReadAllAsync())
Console.WriteLine(value);
}
}
7
The reader consumes the buffered value before completion.
Propagate cancellation
Pass cancellation through pending writes and reads when the operation must stop, and await the tasks owned by the pipeline. A blocked producer needs a completion or cancellation path if a consumer exits early. Propagate an error through the chosen completion policy and release resources in finally or using scopes. Cancellation is cooperative and does not undo items already processed.
Test backpressure
Test a full channel, normal completion with buffered items, early consumer exit, and cancellation of a pending operation. Use controlled tasks and await their completion instead of asserting exact scheduler timing. Verify whether each submitted item was processed, rejected, or deliberately dropped according to the configured policy. A test that reads immediately cannot establish behavior under backpressure.
Define the pipeline contract
A bounded Channel<T> connects producers and consumers while limiting the number of queued items. Before selecting an API, specify capacity, whether every item must be processed, what happens when full, who completes the writer, and how cancellation and failures propagate. Capacity counts queued items, not the size of each item, work already held by consumers, pending producer state or all memory used by the application. A successful write is not proof that a consumer processed the item. If processing has an externally visible effect, define a separate acknowledgement or completion protocol. A queue bound also does not automatically bound an unlimited number of producer tasks waiting to write. Use bounded admission or backpressure at the application boundary and document ownership of items and resources on rejection, drop, cancellation and shutdown.
Choose the full-mode semantics
In the default Wait mode, TryWrite is a nonblocking attempt: when the channel is full it returns false rather than waiting. WriteAsync can wait for space and can be canceled according to its supplied token. DropOldest removes the oldest queued item to make room, DropNewest removes the newest queued item, and DropWrite drops the incoming item. These policies are appropriate only when that loss is acceptable and observable to the application; a write operation’s success should not be interpreted as an acknowledgement that the submitted item will be processed under a dropping policy. Model a full capacity-two queue with named items before selecting a mode, then test exactly which item is retained or dropped. Do not infer the ordering of concurrent producers from task scheduling; any ordering guarantee must follow the documented channel and application contract.
Coordinate completion and draining
Writer completion means no more writes will be accepted; it does not erase items already buffered. A reader can consume remaining items and then observe completion. When multiple producers share a writer, one coordinator should know when all producers have finished before completing it, unless the application deliberately stops the entire pipeline on an error. An individual producer finishing does not prove other producers have stopped. Define how a producer fault is recorded or propagated through completion, and observe producer and consumer tasks rather than treating completion as a substitute for awaiting them. A writer that attempts to write after completion must follow the API’s documented failure behavior. Test a completed empty channel, completion with buffered items, and a producer still active at the proposed completion point.
Provide a path out of blocked work
A producer using Wait mode can remain pending when the channel is full and the consumer stops reading. Pass an appropriate cancellation token to pending reads and writes where supported, and provide a coordinated stop or completion path for early consumer exit. Cancellation is cooperative: requesting it does not prove every task has terminated or undo items already processed. The owner must observe all started operations before disposing dependencies or reporting shutdown complete. Distinguish a canceled wait, a completed channel and a processing fault in the application’s result policy. Do not let one producer independently close a shared channel while others may still write. If a timeout is used as a safeguard, do not use arbitrary delays as proof of an interleaving; controlled gates and explicit task states make the scenario reproducible.
Test item accounting and resource bounds
A meaningful pipeline test records each synthetic item’s fate: processed, rejected, deliberately dropped or still pending under the stated policy. For Wait mode, fill the channel before testing backpressure, verify a second write is pending, then free capacity and await its completion. For drop modes, verify the configured item loss using a controlled sequence and an appropriate observation mechanism. Include normal draining, producer failure, cancellation of a pending operation and early consumer exit. A completed write does not prove the consumer’s side effect succeeded, and channel capacity alone does not bound item payloads or consumer work. Keep tests isolated and await all owned tasks before fixture cleanup. The examples below are synthetic, unexecuted locally, and scoped to C# 14, net10.0 and nullable analysis; they claim no observed scheduler timings.
Walk through an owned channel pipeline
The fragment creates a capacity-two int channel in Wait mode, with two producers and one reader. Producers await WriteAsync with the linked token and the reader consumes ReadAllAsync. Only the reader writes the local total; the four synthetic values are small, and successful completion without cancellation yields 10 without assuming producer interleaving. The channel bounds two queued items, not all application memory.
The coordinator alone completes the writer after both producers finish, or completes it with an error if their join fails. A failing producer or consumer requests linked cancellation so its counterpart does not remain waiting without progress; cancellation does not undo processed items. The combined task observes both producers, the consumer and coordinator before the cancellation source is disposed.
using System;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
static async Task<int> RunAsync(CancellationToken caller)
{
using var stop = CancellationTokenSource.CreateLinkedTokenSource(caller);
var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(2)
{
FullMode = BoundedChannelFullMode.Wait,
SingleWriter = false,
SingleReader = true
});
int total = 0;
async Task Produce(int first)
{
try
{
for (int i = 0; i < 2; i++)
await channel.Writer.WriteAsync(first + i, stop.Token);
}
catch { stop.Cancel(); throw; }
}
async Task Consume()
{
try
{
await foreach (int item in channel.Reader.ReadAllAsync(stop.Token))
total += item;
}
catch { stop.Cancel(); throw; }
}
Task consumer = Consume();
Task firstProducer = Produce(1);
Task secondProducer = Produce(3);
Task producers = Task.WhenAll(firstProducer, secondProducer);
async Task CompleteWriter()
{
try { await producers; channel.Writer.TryComplete(); }
catch (Exception error) { channel.Writer.TryComplete(error); stop.Cancel(); }
}
Task coordinator = CompleteWriter();
Task all = Task.WhenAll(firstProducer, secondProducer, consumer, coordinator);
try { await all; }
catch
{
_ = all.Exception; // retained aggregate is available when faulted
throw;
}
return total;
}
Illustrative fragment, not executed locally; assumes cancellation callbacks do not throw and a suitable C# 14/net10.0 caller.
Define failure policy and limits of the walkthrough
If a producer or consumer faults, the method requests a stop and waits for the started tasks to end. Await can rethrow one exception; inside the method, all.Exception holds the aggregate when the combined task is faulted and is null for pure cancellation. This fragment accesses the aggregate but rethrows only the exception from await; an application needing to expose every failure must add an explicit reporting policy. It makes no claim of durable delivery or retry.
This example assumes one reader, small nonblocking local processing and no custom cancellation callbacks that throw. Cancellation may leave accepted items unprocessed; an application must define accounting or recovery and bound producer admission outside the channel. A real test should control full, fault and cancellation paths and inspect all outcomes without assuming scheduler timing.
20 worked examples
1. Wait mode rejects a nonblocking attempt
Problem: What does TryWrite report for this full channel?
- Both available queue slots are occupied.
- TryWrite does not wait for space in Wait mode.
capacity=2; mode=Wait
queued=[A, B]
no reader runs
attempt=TryWrite(C)
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The attempt returns false and A, B remain queued.
Why this result follows: A nonblocking attempt reports that the item could not be written now.
2. Pending write gains space
Problem: What happens after a reader removes the queued item?
- The full channel makes the second write wait in this controlled sequence.
- Removing A frees the slot, allowing the pending write to complete.
capacity=1; mode=Wait
queued=[A]
start WriteAsync(B); verify pending
reader removes A
await write
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The write completes and B is queued, assuming no cancellation or competing operations.
Why this result follows: Backpressure can delay a write until capacity becomes available.
3. Read creates room for TryWrite
Problem: Can a later nonblocking write succeed after this read?
- The read empties the one-slot queue.
- The subsequent nonblocking write finds available capacity.
capacity=1; mode=Wait
TryWrite(A) succeeds
reader removes A
TryWrite(B) with no competing operation
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The second TryWrite succeeds and B is queued.
Why this result follows: TryWrite reflects capacity at the time of its attempt.
4. DropOldest full mode
Problem: Which item is removed when C arrives?
- A is the oldest queued item.
- The policy drops A to make room for the incoming C.
capacity=2; mode=DropOldest
queued oldest-to-newest=[A, B]
write C; no concurrent reader
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The queue contains B, C.
Why this result follows: DropOldest discards the oldest buffered item when full.
5. DropNewest full mode
Problem: Which queued item is removed when C arrives?
- B is the newest item already in the full queue.
- The policy removes B and admits C.
capacity=2; mode=DropNewest
queued oldest-to-newest=[A, B]
write C; no concurrent reader
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The queue contains A, C.
Why this result follows: DropNewest removes the newest queued item to make room.
6. DropWrite full mode
Problem: Which item is dropped in this full-channel sequence?
- The queue is already full with A and B.
- DropWrite discards the incoming C instead of replacing a queued item.
capacity=2; mode=DropWrite
queued oldest-to-newest=[A, B]
write C; no concurrent reader
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The queue remains A, B and C is dropped.
Why this result follows: The full-mode choice determines the loss semantics.
7. Write is not processing acknowledgement
Problem: What can be claimed after this accepted write?
- The channel accepted A under the stated fixture.
- No consumer processing or acknowledgement has occurred.
write A accepted
consumer has not read A
processing acknowledgement: absent
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: Acceptance is established; processing is not.
Why this result follows: Queue admission and completed work are distinct events.
8. Drain after writer completion
Problem: What does the reader receive under this controlled order?
- Completion prevents further writes but retains already buffered items.
- The reader consumes A then B in the stated queue order and then observes completion.
queued=[A, B]
writer completes normally
reader drains until completion
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The reader receives A, B before normal completion.
Why this result follows: Writer completion and buffer draining are separate stages.
9. Completed empty channel
Problem: What remains for a reader after normal completion with no items?
- The queue contains no buffered item.
- The reader observes normal completion without receiving an item.
queued=[]
writer completes normally
reader starts draining
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The drain produces no items and completes.
Why this result follows: A normally completed empty pipeline has no pending data to drain.
10. Write after completion
Problem: What does a nonblocking write attempt report after completion?
- The writer has been marked complete and accepts no further writes.
- TryWrite reports that it cannot write A.
writer completes normally
attempt=TryWrite(A)
no earlier item is queued
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: TryWrite returns false.
Why this result follows: Completion closes the writer to subsequent items.
11. One producer is still active
Problem: Should the coordinator complete the shared writer now?
- A’s completion does not establish that B has stopped writing.
- Closing the writer now would conflict with the stated policy.
producer A: finished
producer B: active and may write
completion policy: after all producers finish
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: Wait for B before normal writer completion.
Why this result follows: Completion ownership must cover every producer.
12. Coordinator after all producers
Problem: What should happen once all producers complete successfully?
- No producer remains able to write under the fixture.
- The coordinator completes the writer and the consumer can drain the buffered item.
producer A: finished successfully
producer B: finished successfully
coordinator: sole completion owner
buffer: one accepted item
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: Complete the writer, then observe the consumer’s drain and completion.
Why this result follows: Coordinated completion preserves accepted buffered work.
13. Producer fault policy
Problem: What should the owner do when one producer faults?
- The stated policy stops the pipeline rather than treating A as normal completion.
- The owner coordinates stopping B and observes both producers and the consumer.
producer A: faults
producer B: active
policy: stop pipeline, observe all tasks, report failure
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: Report the fault under policy after owned tasks reach observed outcomes.
Why this result follows: Failure propagation and task ownership are explicit application responsibilities.
14. Early consumer exit
Problem: What risk remains for the producer in this controlled fixture?
- No reader remains to free the full slot.
- The pending producer has no stated cancellation or completion path.
capacity=1; mode=Wait
queue full
consumer exits without stop signal
producer awaits WriteAsync
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The producer may remain pending indefinitely.
Why this result follows: Backpressure requires a coordinated stop path when consumption ends early.
15. Cancel a pending write
Problem: What outcome is observed when the controlled pending write is canceled?
- The full queue keeps B’s write pending before cancellation.
- The token-aware wait observes cancellation and the owner awaits its terminal outcome.
capacity=1; mode=Wait; queued=[A]
WriteAsync(B, token) is pending
token canceled; owner awaits write
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The pending write reports cancellation; A remains queued in this fixture.
Why this result follows: Cancellation of a wait does not remove an earlier queued item.
16. Cancellation does not undo processing
Problem: What remains true after this later cancellation?
- The effect for A occurred before the cancellation request.
- The fixture contains no transaction or rollback that reverses it.
consumer processed A and recorded its effect
then pipeline cancellation requested
no rollback protocol specified
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: A remains processed; later cancellation does not undo its effect.
Why this result follows: Cancellation is cooperative control, not automatic rollback.
17. Capacity is not total memory
Problem: Does capacity two bound this whole pipeline to two bytes?
- The capacity counts queued items rather than bytes.
- Each item and the producer or consumer state also consume resources.
channel capacity=2 items
each item payload=1 MB
producer and consumer also hold state
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The two-item bound does not imply a two-byte total-memory bound.
Why this result follows: Queue capacity and total resource usage are different quantities.
18. Pending producers outside the queue
Problem: What remains unbounded in this synthetic design?
- The channel limits the number of buffered items to four.
- It does not eliminate the already-created tasks waiting to write.
channel capacity=4 items
10000 producer tasks created immediately
mode=Wait
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: Pending producer tasks are not bounded by channel capacity alone.
Why this result follows: Admission and queue capacity need separate limits.
19. Controlled backpressure test
Problem: What observation establishes backpressure in this fixture?
- The write cannot complete while the only slot remains occupied in the controlled sequence.
- Reading A creates space and lets the test observe the write’s completion.
fill capacity-one Wait channel with A
start WriteAsync(B) without reading
verify write remains incomplete
read A; await write
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The test observes pending before the read and completion after space is freed.
Why this result follows: Explicit state transitions are stronger than a guessed sleep interval.
20. No inferred producer order
Problem: Can the caller infer which item arrives first from task creation order alone?
- Task creation order does not specify the order of their eventual writes.
- The fixture provides no synchronization that establishes A before B.
producer tasks A and B start concurrently
each writes one item
no ordering coordination specified
Controlled synthetic sequence, not executed locally; it claims no observed scheduler timing.
Expected result: The first item is unspecified by the stated application contract.
Why this result follows: Scheduling assumptions are not an application ordering protocol.
Common errors and fixes
A producer waits forever
- Why it happens
- The consumer exited without cancellation or completion.
- How to fix it
- Provide and propagate a stop path.
- Prevent it next time
- Test early consumer exit.
A write fails after completion
- Why it happens
- The writer completed while a producer was still active.
- How to fix it
- Coordinate completion after producers finish.
- Prevent it next time
- Document completion ownership.
An item is silently lost
- Why it happens
- A dropping policy was chosen without a matching contract.
- How to fix it
- Use the required policy and report drops.
- Prevent it next time
- Test full-channel behavior.
20 practice exercises
1. Why does the second TryWrite fail in the first example?
Show hint
Trace capacity before the second nonblocking attempt.
Show worked solution
The first item fills the capacity-one channel. In Wait mode, TryWrite returns false rather than waiting.
The first successful TryWrite occupies the only slot in the default Wait-mode channel. With no intervening read, the second TryWrite cannot enqueue and immediately returns false; it does not wait for space.
Check your solution
- The first write succeeds and fills the one slot.
- The second write returns false with no read between writes.
2. Who should complete a channel with multiple producers?
Show hint
Completion must account for all active producers.
Show worked solution
A coordinator that knows all producers have finished can complete it. One producer must not close it while another can still write.
A coordinator that observes all producer tasks can complete the shared writer after no producer can write again. Define a separate failure or cancellation policy and await the consumer as it drains buffered items.
Check your solution
- Completion is not issued while another producer may still write.
- The reader drains accepted buffered items under the normal policy.
3. Two producers both receive a true WaitToWriteAsync result for one available slot; producer A writes first. Can producer B assume its next TryWrite succeeds?
Show hint
Readiness is not an exclusive reservation of the slot.
Show worked solution
No. Another producer can consume available capacity before B attempts its write. B must inspect TryWrite and, under the documented policy, wait and retry or stop on completion or cancellation; test the controlled race rather than assuming readiness reserves space.
Check your solution
- B handles a false TryWrite without losing track of its item.
- The test coordinates A’s write between B’s readiness and attempt.
4. A producer uses TryWrite once on a full Wait channel and treats false as success. Design a correct outcome policy.
Show hint
False means the nonblocking attempt did not write the item.
Show worked solution
On false, explicitly reject, retry under a bounded policy, or use a cancellable waiting write according to the application contract. Record the item’s fate and never report it processed merely because an attempt was made.
Check your solution
- A false TryWrite is not reported as accepted or processed.
- The chosen retry or rejection policy is bounded and observable.
5. A capacity-two full queue has oldest A and newest B. A policy requires retaining oldest A and incoming C, while allowing loss of B. Compare DropOldest and DropNewest.
Show hint
Identify which existing buffered item each mode removes.
Show worked solution
DropNewest removes B and admits C, yielding A,C in this controlled sequence. DropOldest would remove A and yield B,C, violating the stated priority; document and observe the intentional loss of B.
Check your solution
- The selected DropNewest policy retains A and C.
- The rejected alternative would discard A.
6. A system must retain all accepted financial commands. Why are drop modes inappropriate, and what additional limit is needed with Wait?
Show hint
A bounded queue does not bound the number of waiting producers.
Show worked solution
Use a no-drop policy such as Wait with explicit cancellation and failure handling, plus bounded admission or backpressure for producers. Define durable acknowledgement separately if accepted commands must survive a process failure.
Check your solution
- The selected full policy does not deliberately discard accepted commands.
- Pending admission and durability are addressed separately.
7. Two readers receive a true WaitToReadAsync result for one queued item; reader A removes it before reader B calls TryRead. Can B assume success, and how should it handle completion?
Show hint
Readiness is not an exclusive reservation of the item.
Show worked solution
B must inspect TryRead: A can consume the only item first, making B’s attempt fail. Under the reader contract, wait again while the channel can produce data and handle completion or cancellation; test the interleaving with explicit signals.
Check your solution
- B handles a false TryRead without inventing an item.
- The test coordinates A’s read between B’s readiness and attempt.
8. A DropWrite channel is full with two audit events. The producer sees its write operation complete. Can it claim the incoming event was processed?
Show hint
DropWrite discards the incoming item when full.
Show worked solution
No. In the full-channel fixture the incoming event is dropped, and write completion is not processing acknowledgement. Choose a no-drop and durable acknowledgement design if the audit contract requires every event.
Check your solution
- The incoming event is not treated as processed.
- A lossless requirement uses an appropriate alternative policy.
9. All producers finished and the coordinator completed the writer, but the consumer fails while processing the second of three buffered items. Define the final report and recovery decision.
Show hint
Writer completion does not prove successful draining or processing.
Show worked solution
Record the first item as processed, the second as failed or uncertain according to the consumer contract, and account for the third separately. Observe the consumer fault and invoke the documented retry or recovery policy; do not report full success merely because producers completed.
Check your solution
- The consumer fault is observed and reported.
- All three item outcomes are accounted for without claiming full processing.
10. A channel completes with three buffered items, but the consumer stops after one. What must shutdown policy address?
Show hint
Completion does not mean every item was processed.
Show worked solution
Account for the two unprocessed buffered items: drain them, explicitly discard them under an allowed policy, or transfer them to a recovery mechanism. Observe the consumer and report the actual outcome rather than calling completion full processing.
Check your solution
- All three item fates are accounted for.
- The report distinguishes writer completion from processing.
11. A producer faults while another is blocked on a full Wait channel. Design an error and shutdown sequence.
Show hint
A blocked producer needs an explicit stop path.
Show worked solution
The coordinator records the fault, signals cancellation or completion according to the pipeline policy, and awaits both producers and the consumer before releasing shared dependencies. Define treatment of buffered and already processed items.
Check your solution
- The blocked producer reaches an observed terminal outcome.
- The original fault and buffered-item policy are recorded.
12. A consumer exits early after processing A while B is queued and C is waiting to write. Define item accounting.
Show hint
These three items occupy different lifecycle states.
Show worked solution
Record A as processed, B as queued but not yet processed, and C as a pending write until its outcome is observed. Stop or recover the pipeline under its policy and do not count B or C as completed work.
Check your solution
- A is reported as processed.
- B and C are tracked separately until their final outcomes.
13. A pending WriteAsync is canceled, but the owner immediately disposes the consumer’s resource. Explain the missing step.
Show hint
A cancellation request is not a task join.
Show worked solution
Observe the canceled write and await every started producer and consumer that might use the resource before disposal. Record any unrelated fault separately; do not assume the request itself stopped all tasks.
Check your solution
- Every started task reaches an observed outcome.
- Shared resources outlive their users.
14. A channel holds four 5 MB items and producers retain additional payloads while waiting. Explain the memory bound.
Show hint
Capacity counts buffered items, not all payload ownership.
Show worked solution
The buffered payload alone can represent 20 MB under the fixture, while pending producer and consumer state add more. Bound item size and admission as well as channel capacity, and measure actual retention under the workload.
Check your solution
- The buffered payload is 20 MB in the fixture.
- Pending and consumer memory are covered by separate limits.
15. A pending write can race with both cancellation and a reader freeing space. Design two deterministic tests with distinct ordered outcomes.
Show hint
Control whether cancellation or the read is observed first.
Show worked solution
Use explicit gates to test cancellation while the channel remains full, and separately free space and await the write before requesting cancellation. Assert each documented outcome and account for the item; do not assume an uncontrolled race always chooses one winner.
Check your solution
- The cancellation-first test observes the canceled pending write.
- The space-first test observes a completed write before cancellation.
16. A write succeeds, but the consumer later fails while saving the item. Design an acknowledgement contract.
Show hint
Admission and durable processing are separate events.
Show worked solution
Return or record a separate processing outcome keyed by the item or operation, and define retry and idempotency for a failed save. Do not treat channel write completion as proof of a durable effect.
Check your solution
- A failed save is distinguishable from accepted admission.
- Retry behavior avoids duplicate logical effects under the chosen protocol.
17. Two producers require a total sequence A1, B1, A2, but run concurrently. Design an ordering protocol.
Show hint
Task creation order is not the required coordination.
Show worked solution
Use an explicit coordinator or sequence-number protocol that enforces the required order before publishing, and define failure when a predecessor is missing. Test controlled out-of-order producer readiness without assuming scheduler order.
Check your solution
- The emitted sequence is A1, B1, A2.
- Missing or failed predecessor behavior is documented.
18. A pipeline has one producer and one consumer today; tomorrow a second producer is added. What configuration and tests need review?
Show hint
Single-writer assumptions must match actual use.
Show worked solution
Review the channel’s SingleWriter setting and any application ownership assumptions, then coordinate both producers and completion under the supported multiwriter design. Test concurrent writes and faulted producer shutdown with bounded synthetic work.
Check your solution
- The configuration matches the actual number of writers.
- Completion waits for or handles both producer outcomes.
19. A DropOldest queue discards a disposable item. What ownership question must be answered?
Show hint
Dropping an item is not automatically a disposal protocol.
Show worked solution
Define who observes the drop and disposes or transfers the dropped item, using a supported observation mechanism and a single-owner policy. Test that a dropped synthetic resource is released exactly as documented without disposing retained items.
Check your solution
- The dropped item has an explicit cleanup owner.
- Retained items are not disposed by the drop path.
20. A pipeline stress test passes 1,000 synthetic runs. Draft a bounded evidence statement.
Show hint
A finite sample does not cover every schedule.
Show worked solution
Report the capacity, full mode, producer and consumer counts, workload, runtime and observed outcomes for those runs. Do not claim every interleaving is safe; retain controlled tests for full, cancellation, fault and completion paths.
Check your solution
- The report names the tested workload and run count.
- Controlled failure and completion paths remain in the suite.
Key takeaways
- Bounded capacity requires an explicit full policy.
- Coordinate completion and cancellation across the pipeline.
- Full-mode choice determines waiting or item loss.
- Writer completion and processing acknowledgement are separate.
- Cancellation requests must be followed by observed task completion.