<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Darshan patel on Medium]]></title>
        <description><![CDATA[Stories by Darshan patel on Medium]]></description>
        <link>https://medium.com/@darshan.patel_20127?source=rss-039d5e9b6cbf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S-hV1DmALig1n7TVs4VmxA.jpeg</url>
            <title>Stories by Darshan patel on Medium</title>
            <link>https://medium.com/@darshan.patel_20127?source=rss-039d5e9b6cbf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 10:22:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@darshan.patel_20127/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[High-Performance Background Processing in .NET 10 Using Channels]]></title>
            <link>https://medium.com/simform-engineering/high-performance-background-processing-in-net-10-using-channels-b0a17f38593b?source=rss-039d5e9b6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0a17f38593b</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Darshan patel]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 05:24:09 GMT</pubDate>
            <atom:updated>2026-08-03T05:24:09.179Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Master System.Threading.Channels for scalable background workers, producer-consumer patterns, and high-throughput .NET applications.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkUU_u6kEdGlAPYgYg1s4w.png" /></figure><p>Modern .NET applications constantly process asynchronous workloads behind the scenes — API request buffering, telemetry ingestion, event processing, notification dispatching, and long-running background jobs. As systems scale, efficiently coordinating producers and consumers without blocking threads becomes critical for throughput, responsiveness, and graceful shutdown handling.</p><p>Most .NET developers have built a background queue at some point — a ConcurrentQueue&lt;T&gt; paired with a SemaphoreSlim, or a BlockingCollection&lt;T&gt; with a dedicated consumer thread. They work well for many scenarios, but they rely on blocking synchronization patterns and require more manual lifecycle management compared to modern asynchronous primitives like Channels. They&#39;re awkward to test, and graceful shutdown is always an afterthought.</p><p>System.Threading.Channels ships in the BCL (Base Class Library), requires zero NuGet packages, and replaces all of that with a thread-safe, async-first pipeline primitive. Once you understand the strengths and limitations of Channels, they often become a simpler and safer alternative to manually managing asynchronous producer-consumer pipelines.</p><p><strong>Why Use Channels in .NET 10?</strong></p><p>Although <strong>System.Threading.Channels</strong> has been available since earlier versions of .NET, it remains one of the most efficient ways to implement in-process background processing in .NET 10 applications.</p><p>With .NET 10’s improved runtime performance, async infrastructure, and hosting model, Channels integrate naturally with modern BackgroundService and ASP.NET Core applications.</p><h3>Table of Contents</h3><ol><li>What Are Channels?</li><li>Core Components</li><li>Types of Channels</li><li>When to Use Channels (and When Not To)</li><li>Implementation Techniques</li><li>The Channel API</li><li>Getting Capacity Right</li><li>Performance Hints &amp; Benchmarks</li><li>Common Mistakes</li><li>How It Stacks Up</li><li>Real-World Use Cases</li><li>Code Examples</li><li>Conclusion</li></ol><h3>What Are Channels?</h3><p>A Channel&lt;T&gt; is a thread-safe, in-process pipe that connects producers and consumers asynchronously. Producers write items through a ChannelWriter&lt;T&gt; and consumers read them through a ChannelReader&lt;T&gt;. The runtime handles all synchronization internally — no locks, no manual signalling, no spin loops required.</p><p>Channels also support <strong>back-pressure</strong>, which means if consumers are slower than producers, the channel automatically slows down or blocks writers so memory doesn’t grow uncontrollably.</p><pre>Producer --&gt; ChannelWriter&lt;T&gt; --&gt; [ buffer ] --&gt; ChannelReader&lt;T&gt; --&gt; Consumer</pre><blockquote>The core problem Channels solve is coordinating work between parts of your application that run at different speeds, without blocking threads or writing complex synchronization code manually.</blockquote><h3>Core Components</h3><ol><li>Channel&lt;T&gt; : The pipe itself — holds the buffer and exposes the writer and reader</li><li>ChannelWriter&lt;T&gt; : Producer end — write items into the channel</li><li>ChannelReader&lt;T&gt; : Consumer end — read items out of the channel</li></ol><p><strong>Writing</strong></p><ol><li>await writer.WriteAsync(item, ct) : Async write. Suspends the caller if the channel is full.</li><li>writer.TryWrite(item)Non-blocking attempt. Returns false if full</li></ol><p><strong>Reading</strong></p><ol><li>await foreach (var x in reader.ReadAllAsync(ct)) : Idiomatic drain loop. exits when channel is sealed and empty.</li><li>await reader.WaitToReadAsync(ct) : Suspends until at least one item is available; useful for custom batching.</li><li>reader.TryRead(out var item) : Non-blocking read attempt</li></ol><p><strong>Completion</strong></p><ol><li>writer.TryComplete() : Seals the channel — no more writes allowed; safe to call multiple times.</li><li>writer.TryComplete(exception) : Faults the channel; the exception propagates to all active readers.</li><li>await reader.Completion : Task that completes when the channel is sealed and its buffer is empty</li></ol><blockquote><strong><em>Always call </em></strong><strong><em>TryComplete() in a </em></strong><strong><em>finally block.</em></strong><em> If you skip it on an error path, every consumer waits forever.</em></blockquote><h3>Types of Channels</h3><p>There are three channel types to choose from depending on your scenario:</p><ul><li><strong>Unbounded</strong> — No capacity limit. Writes never block and complete synchronously. Use only when the producer rate is guaranteed to be manageable, or as a starting point before profiling.</li><li><strong>Bounded</strong> — Fixed capacity with a configurable strategy for when the buffer is full (FullMode). This is the recommended default for production because it prevents runaway memory growth.</li><li>Full Modes explained below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xrNVkq_ZJpja1vBM9KfWQ.png" /></figure><ul><li><strong>Prioritized</strong> (.NET 8+) — Unbounded, but items are dequeued in priority order using a supplied IComparer&lt;T&gt;. Critical work is always processed before routine tasks regardless of arrival order.</li></ul><h3>When to Use Channels</h3><h4>Use Channels when</h4><ul><li>A producer and consumer run at different speeds and you need the slower side to naturally apply pressure on the faster side without manual signalling code.</li><li>You want to offload work from a hot path (such as an HTTP request thread) without blocking it.</li><li>You need a multi-stage pipeline where each stage runs concurrently and independently.</li><li>You require a clean, race-free shutdown — TryComplete() combined with reader.Completion guarantees all in-flight items are processed before the application exits.</li><li>You need zero external dependencies — System.Threading.Channels ships in-box since .NET Core 3.0.</li></ul><h3>When NOT to Use Channels</h3><blockquote>⚠️ <strong>Important:</strong> System.Threading.Channels is an <strong>in-memory coordination primitive</strong>, not a distributed messaging system.</blockquote><ul><li>Items are lost if the process crashes</li><li>Channels do not provide persistence or durability</li><li>Channels do not support cross-process communication</li><li>They are <strong>not</strong> a replacement for Kafka, RabbitMQ, Azure Service Bus, or NATS<strong>.</strong></li></ul><h4>Do not use Channels when</h4><ul><li><strong>Cross-process communication is needed</strong> — use RabbitMQ, Azure Service Bus, Kafka, or NATS instead.</li><li><strong>Durability is required</strong> — channels are in-memory only. A process crash loses all buffered items. Use a persistent message broker or an outbox pattern.</li><li><strong>Broadcasting the same item to multiple independent subscribers</strong> — consider TPL Dataflow’s BroadcastBlock&lt;T&gt; or IObservable&lt;T&gt;.</li><li><strong>CPU-bound parallel work with no producer/consumer split</strong> — Parallel.ForEachAsync or Task.WhenAll are a better fit.</li></ul><blockquote><strong><em>Rule of thumb:</em></strong><em> If you find yourself writing a </em><em>BlockingCollection or a </em><em>ConcurrentQueue + SemaphoreSlim pair to coordinate async work within one process, a Channel is almost certainly the cleaner solution.</em></blockquote><h3>Implementation Techniques</h3><h4>The Channel API</h4><p><strong>Quick Reference</strong></p><pre>1. Create unbounded               Channel.CreateUnbounded&lt;T&gt;()<br>2. Create bounded (cap 100)       Channel.CreateBounded&lt;T&gt;(100)<br>3. Create prioritized (.NET 8+)   Channel.CreateUnboundedPrioritized&lt;T&gt;(options)<br>4. Async write                    await writer.WriteAsync(item, ct)<br>5. Sync write attempt             writer.TryWrite(item)<br>6. Drain all items                await foreach (var x in reader.ReadAllAsync(ct))<br>7. Custom batching loop           while (await reader.WaitToReadAsync(ct))<br>                                  { <br>                                    while (reader.TryRead(out var x))<br>                                    ...<br>                                  }<br>8. Non-blocking read attempt      reader.TryRead(out var item)<br>9. Seal channel                   writer.TryComplete()<br>10.Fault channel                  writer.TryComplete(exception)<br>11.Await full drain               await reader.Completion<br>12.Buffered item count            reader.CanCount ? reader.Count : -1</pre><h3>Getting Capacity Right</h3><p>Picking the right capacity for a bounded channel is one of the most impactful decisions in channel design.</p><p><strong>The sizing formula</strong> is based on the rate of production and how long consumption takes:</p><pre>MinCapacity          = ProducerRate (items/s) x ConsumerP99Latency (s)<br>RecommendedCapacity  = MinCapacity x 3  (burst headroom)</pre><p>Example: 1,000 items/s producer, 200 ms P99 consumer latency:</p><pre>MinCapacity          = 1000 x 0.2 = 200 items<br>RecommendedCapacity  = 200 x 3 = 600 items</pre><ul><li>Never use unbounded channels in production without monitoring. Even a small, sustained rate mismatch accumulates unboundedly over hours.</li><li>If reader.Count is consistently near capacity, add more consumer workers before increasing capacity.</li><li>If WriteAsync frequently suspends, profile first — the consumer may be the bottleneck, not the channel size.</li></ul><h3>Performance Hints &amp; Benchmarks</h3><p>The following figures are representative of single-producer / single-consumer, in-process, Intel Core i5, .NET 10, with 1 million items. They illustrate relative ordering, not absolute guarantees — always benchmark your specific workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1_QtNZxfdp64hmnY3cxsw.png" /></figure><p>ConcurrentQueue can have higher raw enqueue/dequeue throughput in tight loops, but Channels often outperform it in real async workloads due to built-in back-pressure and scheduling behavior.</p><blockquote><em>⚠️ Throughput numbers collapse when items carry real I/O or CPU work — at that point, back-pressure and correctness matter far more than raw enqueue/dequeue speed.</em></blockquote><p>Set these in the channel options for measurable gains:</p><ul><li><strong>SingleReader = true / </strong><strong>SingleWriter = true</strong> — Activates a faster, lock-free internal code path when there is exactly one reader or writer. Free performance when accurate.</li><li><strong>AllowSynchronousContinuations = true</strong> — Continuations run inline on the completing thread, reducing latency.<strong> Leave this </strong><strong>false unless a profiler confirms it helps </strong>— it can cause subtle issues if any continuation does blocking work.</li><li><strong>reader.CanCount ? reader.Count : -1</strong> — Use for health-check dashboards only, not for flow control (it&#39;s a point-in-time snapshot).</li></ul><h3>How It Stacks Up</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kji2eFfpYyBtYqp46mXVyg.png" /></figure><ul><li><strong>Highest raw throughput:</strong> ConcurrentQueue&lt;T&gt; with a spin-wait — at the cost of 100% CPU on the consumer thread.</li><li><strong>Best async latency and throughput balance:</strong> Channel&lt;T&gt; with SingleReader/SingleWriter hints.</li><li><strong>Production default:</strong> Bounded Channel&lt;T&gt; with FullMode.Wait — safe, async-first, and performant for the vast majority of workloads.</li></ul><p>Choose TPL Dataflow when you need built-in broadcasting or a declarative graph-style pipeline topology. Use a distributed broker when producers and consumers live in separate processes.</p><h3>Common Mistakes</h3><h4>1. Forgetting writer.TryComplete()</h4><p>If the writer is never sealed, ReadAllAsync and reader.Completion wait forever.</p><pre>try   { /* write items */ }<br>finally { writer.TryComplete(); }  // always in finally</pre><h4>2. Multiple Producers Racing to Complete</h4><p>When multiple producers share one writer, only the last one should seal the channel. Coordinate with Interlocked:</p><pre>if (Interlocked.Decrement(ref _activeProducers) == 0)<br>    writer.TryComplete();  // only the last producer seals the channel</pre><h4>3. Swallowing OperationCanceledException</h4><p>Always re-throw cancellation so cooperative shutdown works correctly:</p><pre>catch (OperationCanceledException) { throw; }<br>catch (Exception ex)               { /* handle */ }</pre><h4>4. Downstream Stages Hanging After an Upstream Fault</h4><p>If an upstream stage throws but never seals its output channel, every downstream stage blocks indefinitely. Use ContinueWith to propagate completion unconditionally:</p><pre>_ = uploaderTask.ContinueWith(<br>    t =&gt; nextChannel.Writer.TryComplete(t.Exception?.InnerException),<br>    TaskScheduler.Default);</pre><h3>Real-World Use Cases</h3><h4>1. Background Task Queue</h4><p>Offload heavy work from HTTP request threads to background workers. IHostedService combined with Channel&lt;T&gt; is the cleanest zero-dependency intra-process pattern.</p><pre>HTTP Request --&gt; ChannelWriter --&gt; [bounded channel] --&gt; ChannelReader --&gt; Worker(s)</pre><p><strong>Key considerations:</strong> Set a bounded capacity with FullMode.Wait so callers are naturally throttled when the worker is busy. Use SingleReader = true if a single background service drains the queue.</p><h4>2. Multi-Stage ETL Pipeline</h4><p>Each transformation stage (fetch, parse, validate, save) runs concurrently. Channels between stages decouple them and allow each stage to progress at its own pace. Faults in one stage propagate cleanly to downstream stages via TryComplete(exception).</p><pre>Fetch --&gt; Channel --&gt; Parse --&gt; Channel --&gt; Validate --&gt; Channel --&gt; Save</pre><p><strong>Key consideration:</strong> Each stage should seal its output channel in a finally block to guarantee downstream stages always terminate.</p><h4>3. Real-Time Data Streaming</h4><p>Sensor readings, stock ticks, or log events that arrive faster than they can be processed. Use BoundedChannelFullMode.DropOldest so the consumer always sees the most recent data rather than falling further behind.</p><p><strong>Key consideration:</strong> DropOldest trades completeness for freshness — only use it when stale data has no value.</p><h4>4. Fan-Out Work Distribution</h4><p>A single producer writes items; multiple competitive consumers share one ChannelReader&lt;T&gt;. Each item goes to exactly one consumer with no additional routing code required.</p><p><strong>Key consideration:</strong> All consumers read from the same reader. There is no need to create separate channels per consumer — the channel handles distribution automatically.</p><h3>Code Examples</h3><p>System.Threading.Channels is in-box <em>since .NET Core 3.0</em>. For .NET Standard 2.0 or .NET Framework:</p><pre>dotnet add package System.Threading.Channels</pre><p>Full runnable examples are available in the <a href="https://github.com/dotnet-simformsolutions/high-performance-channels-dotnet">GitHub repository.</a></p><h4>Example 1 — Basic Write, Read, and Complete</h4><pre>var channel = Channel.CreateUnbounded&lt;string&gt;();<br><br>// Producer<br>await channel.Writer.WriteAsync(&quot;Hello&quot;);<br>await channel.Writer.WriteAsync(&quot;World&quot;);<br><br>channel.Writer.TryComplete();   // seal: no more items<br><br>// Consumer - ReadAllAsync exits when the channel is sealed and drained<br>await foreach (var message in channel.Reader.ReadAllAsync())<br>    Console.WriteLine(message);<br><br>// Output:<br>// Hello<br>// World</pre><h4>Example 2 — Bounded Channel with Fan-Out</h4><p>A bounded channel combines back-pressure with fan-out consumers, making it ideal for high-throughput background processing systems.</p><ul><li><strong>Back-pressure:</strong><br>The channel capacity is limited to 10 items. Producers generate data faster than consumers can process it, so once the buffer fills, WriteAsync automatically pauses producers until space becomes available. No polling or manual signalling required.</li><li><strong>Producer coordination:</strong><br>Multiple producers share the same writer, so only the final producer should complete the channel. Interlocked.Decrement provides a lightweight lock-free way to determine which producer finishes last.</li><li><strong>Fan-out:</strong><br>Multiple consumers call ReadAllAsync on the same ChannelReader&lt;T&gt;. Each item is automatically distributed to exactly one consumer, without requiring custom routing or partitioning logic.</li></ul><pre>var channel = Channel.CreateBounded&lt;int&gt;(new BoundedChannelOptions(10)<br>{<br>    FullMode = BoundedChannelFullMode.Wait<br>});<br><br>int activeProducers = 2;<br><br>// 2 fast producers - WriteAsync suspends automatically when the buffer is full<br>var producers = Enumerable.Range(1, 2).Select(id =&gt; Task.Run(async () =&gt;<br>{<br>    for (int i = 0; i &lt; 10; i++)<br>    {<br>        await channel.Writer.WriteAsync(id * 100 + i);<br>        await Task.Delay(30);<br>    }<br>    if (Interlocked.Decrement(ref activeProducers) == 0)<br>        channel.Writer.TryComplete();   // last producer seals the channel<br>})).ToArray();<br><br>// 3 competitive consumers - each item goes to exactly one consumer<br>var consumers = Enumerable.Range(1, 3).Select(id =&gt; Task.Run(async () =&gt;<br>{<br>    await foreach (var item in channel.Reader.ReadAllAsync())<br>    {<br>        Console.WriteLine($&quot;[Consumer {id}] {item}&quot;);<br>        await Task.Delay(100);<br>    }<br>})).ToArray();<br><br>await Task.WhenAll([..producers, ..consumers]);<br>Console.WriteLine(&quot;Done.&quot;);</pre><h4>Example 3 — Multi-Stage Pipeline (Fetch, Parse, Save)</h4><pre>Fetch → Parse → Validate → Save</pre><p>Each stage runs concurrently, with channels providing independent back-pressure and clean fault propagation between stages.</p><p>This example models a realistic ETL pipeline using multiple processing stages connected through channels.</p><p><strong>Why separate channels?</strong></p><p>Each channel acts as a buffer between stages, allowing every stage to run independently:</p><ol><li>If Parse slows down, items accumulate in parseCh</li><li>Back-pressure naturally throttles upstream producers</li><li>Faster stages cannot overwhelm slower ones</li></ol><p><strong>Fault propagation</strong></p><p>Each stage follows the same structure:</p><ol><li>Read from input channel</li><li>Process items inside try</li><li>Capture failures</li><li>Complete the output channel in finally</li></ol><p>If one stage fails, downstream channels are faulted automatically, preventing deadlocks or consumers waiting forever for new items.</p><p><strong>Strongly-typed stages</strong></p><p>Using separate record types like RawData and ParsedModel creates explicit contracts between stages and makes transformations safer at compile time.</p><pre>record RawData(string Url, string Json);<br>record ParsedModel(int Id, string Name);<br><br>var fetchCh = Channel.CreateBounded&lt;string&gt;(32);<br>var parseCh = Channel.CreateBounded&lt;RawData&gt;(16);<br>var saveCh  = Channel.CreateBounded&lt;ParsedModel&gt;(16);<br><br>async Task SeedAsync()<br>{<br>    foreach (var url in new[] { &quot;https://api.example.com/1&quot;, &quot;https://api.example.com/2&quot; })<br>        await fetchCh.Writer.WriteAsync(url);<br>    fetchCh.Writer.TryComplete();<br>}<br><br>async Task FetchStageAsync()<br>{<br>    Exception? fault = null;<br>    try<br>    {<br>        await foreach (var url in fetchCh.Reader.ReadAllAsync())<br>        {<br>            var json = $&quot;{{\&quot;id\&quot;:{url.Last()},\&quot;name\&quot;:\&quot;Item {url.Last()}\&quot;}}&quot;;<br>            await parseCh.Writer.WriteAsync(new RawData(url, json));<br>        }<br>    }<br>    catch (Exception ex) { fault = ex; }<br>    finally { parseCh.Writer.TryComplete(fault); }<br>}<br><br>async Task ParseStageAsync()<br>{<br>    Exception? fault = null;<br>    try<br>    {<br>        await foreach (var raw in parseCh.Reader.ReadAllAsync())<br>        {<br>            var model = JsonSerializer.Deserialize&lt;ParsedModel&gt;(raw.Json)!;<br>            await saveCh.Writer.WriteAsync(model);<br>        }<br>    }<br>    catch (Exception ex) { fault = ex; }<br>    finally { saveCh.Writer.TryComplete(fault); }<br>}<br><br>async Task SaveStageAsync()<br>{<br>    await foreach (var model in saveCh.Reader.ReadAllAsync())<br>        Console.WriteLine($&quot;[Save] Id={model.Id}, Name={model.Name}&quot;);<br>}<br><br>await Task.WhenAll(SeedAsync(), FetchStageAsync(), ParseStageAsync(), SaveStageAsync());<br><br>Console.WriteLine(&quot;Pipeline complete.&quot;);</pre><h4>Example 4 — ASP.NET Core Background Service</h4><p>The canonical pattern for .NET web apps — enqueue from request threads without blocking; a background service drains and processes:</p><p>This example shows the recommended way to integrate a channel into an ASP.NET Core application using IHostedService.</p><p><strong>Channel configuration choices:</strong></p><ul><li>Capacity 1024 sets the maximum number of log entries that can be buffered before EnqueueAsync starts suspending callers. Tune this value based on expected burst size and how long storage.SaveAsync takes.</li><li>FullMode.Wait means a request handler that calls EnqueueAsync will pause (not block a thread — it awaits) if the buffer is full. This is the correct production default: it propagates back-pressure to the caller rather than silently dropping data.</li><li>SingleReader = true is safe here because only ConsumeAsync reads from the channel. It allows the runtime to use a faster, lock-free internal code path with zero extra work on your part.</li></ul><p><strong>The </strong><strong>EnqueueAsync method</strong> is ValueTask-returning, matching WriteAsync directly. In the common case where the channel has space, WriteAsync completes synchronously and no allocation occurs — the ValueTask wraps the synchronous result. Only when the buffer is full does an actual async suspension happen.</p><p><strong>Shutdown sequence</strong> — order matters:</p><ol><li>StopAsync calls TryComplete() first. This seals the writer so no new entries can be enqueued after shutdown begins.</li><li>It then awaits _consumerTask. Because the channel is sealed, ReadAllAsync inside ConsumeAsync will drain all remaining buffered entries and then exit — none are silently discarded.</li></ol><p>Without step 1, the consumer loop would never exit. <br>Without step 2, the host could terminate mid-drain, losing buffered entries.</p><pre>public record LogEntry(Guid Id, string Message, DateTime Timestamp);<br><br>public sealed class LogProcessorService(ILogStorage storage, ILogger&lt;LogProcessorService&gt; logger)<br>    : IHostedService, IAsyncDisposable<br>{<br>    private readonly Channel&lt;LogEntry&gt; _channel = Channel.CreateBounded&lt;LogEntry&gt;(<br>        new BoundedChannelOptions(1024)<br>        {<br>            FullMode     = BoundedChannelFullMode.Wait,<br>            SingleReader = true<br>        });<br>   <br>    private Task _consumerTask = Task.CompletedTask;<br>   <br>    // Called by request handlers - non-blocking; callers suspend when the buffer is full<br>    public ValueTask EnqueueAsync(LogEntry entry, CancellationToken ct = default)<br>        =&gt; _channel.Writer.WriteAsync(entry, ct);<br>    <br>    public Task StartAsync(CancellationToken cancellationToken)<br>    {<br>        _consumerTask = ConsumeAsync(cancellationToken);<br>        return Task.CompletedTask;<br>    }<br>    public async Task StopAsync(CancellationToken cancellationToken)<br>    {<br>        _channel.Writer.TryComplete();                    // 1. no more writes<br>        await _consumerTask.WaitAsync(cancellationToken); // 2. drain, but respect host shutdown timeout<br>    }<br>    private async Task ConsumeAsync(CancellationToken ct)<br>    {<br>        await foreach (var entry in _channel.Reader.ReadAllAsync(ct))<br>        {<br>            try   { await storage.SaveAsync(entry, ct); }<br>            catch (Exception ex)<br>            {<br>                logger.LogError(ex, &quot;Failed to persist log entry {Id}&quot;, entry.Id);<br>            }<br>        }<br>    }<br>    public ValueTask DisposeAsync() <br>    { <br>     _channel.Writer.TryComplete(); <br>     return ValueTask.CompletedTask;<br>    } <br>}<br>// Program.cs:<br>// builder.Services.AddSingleton&lt;ILogStorage, SqlLogStorage&gt;();<br>// builder.Services.AddSingleton&lt;LogProcessorService&gt;();<br>// builder.Services.AddHostedService(sp =&gt; sp.GetRequiredService&lt;LogProcessorService&gt;());<br><br>// DI scope note<br>// Avoid capturing scoped services inside queued work items. <br>// Create a scope using IServiceScopeFactory inside the consumer when scoped dependencies are required. </pre><h4>Example 5 — Prioritized Channel (.NET 8+)</h4><p>Items are dequeued in ascending priority order regardless of insertion order:</p><p>This example shows Channel.CreateUnboundedPrioritized&lt;T&gt;. Unlike a standard channel, which is strictly FIFO, the prioritized channel maintains an internal min-heap. When the consumer reads, it always receives the item with the lowest priority number first — regardless of the order items were written.</p><p><strong>The comparer delegate</strong> tells the channel how to rank items. a.Priority.CompareTo(b.Priority) returns a negative value when a has a lower number than b, so lower numbers surface first. To reverse the order (highest priority first), swap a and b in the comparison.</p><p><strong>Write order vs. read order:</strong> All three items are written in order Priority 3 → 1 → 2, but they are always read back as 1 → 2 → 3. This guarantee holds regardless of timing or concurrency — the internal heap ensures it.</p><p><strong>When to use this over a bounded channel:</strong> Use a prioritized channel when some work is genuinely more urgent than other work and you cannot afford to let a high-priority item sit behind a backlog of low-priority items. A common example is mixing critical alerts with routine housekeeping tasks in the same worker queue.</p><p>Note that the channel is unbounded here, which is fine for controlled scenarios. Because prioritized channels are currently unbounded, production systems should carefully control the rate of incoming work or implement external admission controls to avoid <strong>unlimited memory growth</strong>.</p><pre>record WorkItem(int Priority, string Payload);<br>var channel = Channel.CreateUnboundedPrioritized(<br>    new UnboundedPrioritizedChannelOptions&lt;WorkItem&gt;<br>    {<br>        Comparer = Comparer&lt;WorkItem&gt;.Create((a, b) =&gt; a.Priority.CompareTo(b.Priority))<br>    });<br>await channel.Writer.WriteAsync(new WorkItem(3, &quot;Nightly report&quot;));<br>await channel.Writer.WriteAsync(new WorkItem(1, &quot;Critical alert&quot;));<br>await channel.Writer.WriteAsync(new WorkItem(2, &quot;Standard request&quot;));<br>channel.Writer.TryComplete();<br>await foreach (var item in channel.Reader.ReadAllAsync())<br>    Console.WriteLine($&quot;[Priority {item.Priority}] {item.Payload}&quot;);<br>// Output (always priority order, regardless of write order):<br>// [Priority 1] Critical alert<br>// [Priority 2] Standard request<br>// [Priority 3] Nightly report</pre><p><a href="https://github.com/dotnet-simformsolutions/high-performance-channels-dotnet">GitHub Repository — Complete working POC</a></p><h3>Conclusion</h3><p>System.Threading.Channels is one of the most underused APIs in .NET. It ships in the BCL (Base Class Library) with no external dependencies and solves producer-consumer coordination cleanly — without blocking threads, without manual synchronization, and with a solid built-in story for dealing with slow consumers and graceful shutdown.</p><p>If you’re building any form of background processing in .NET, Channels should be your first consideration before reaching for a third-party library or a distributed message broker.</p><h3>Decision Checklist</h3><p>Use this checklist to decide whether Channel&lt;T&gt; is the right fit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lt0gl2tvN2K3NuAT348gfw.png" /></figure><p><strong>Key rules to remember:</strong></p><ul><li>Always use <strong>bounded channels in production</strong>. An unbounded channel with even a small sustained rate mismatch will grow until you hit an out-of-memory condition.</li><li><strong>TryComplete() belongs in a </strong><strong>finally block</strong> — always. Consumers will hang indefinitely if it is skipped on any error path.</li><li><strong>Set </strong><strong>SingleReader/</strong><strong>SingleWriter when accurate</strong> — it activates a lock-free internal path at no cost.</li><li><strong>Pass </strong><strong>CancellationToken everywhere.</strong> Graceful shutdown is only graceful if every stage cooperates.</li><li><strong>Channels are not durable queues.</strong> A process crash loses all in-flight items.</li></ul><p>Building scalable background processing is a key part of designing reliable distributed systems. <a href="https://www.simform.com/">Simform</a> applies modern .NET patterns such as System.Threading.Channels to build asynchronous processing pipelines that improve throughput, simplify concurrency, and support resilient application architectures.</p><p><strong>References</strong></p><ul><li><a href="https://learn.microsoft.com/en-us/dotnet/core/extensions/channels">System.Threading.Channels — Microsoft Docs</a></li><li><a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.channels.channel-1">Channel&lt;T&gt; API Reference</a></li></ul><p><em>System.Threading.Channels · .NET 10 · 2026</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0a17f38593b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/simform-engineering/high-performance-background-processing-in-net-10-using-channels-b0a17f38593b">High-Performance Background Processing in .NET 10 Using Channels</a> was originally published in <a href="https://medium.com/simform-engineering">Simform Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>