Skip to content
The Chat Archive
deepseek-r1-0528· DeepSeek LMArena Human Preference 140K

Create a C# code sample based on .net framework for an async producer consumer pattern…

  1. User

    Create a C# code sample based on .net framework for an async producer consumer pattern where the consumer uses a background task.

  2. Assistant

    Here's a C# implementation of an async producer-consumer pattern using .NET Framework 4.8 with a background task consumer:

    using System;
    using System.Collections.Concurrent;
    using System.Threading;
    using System.Threading.Tasks;
    
    public class AsyncProducerConsumer
    {
        private readonly BlockingCollection<int> _buffer = new BlockingCollection<int>(boundedCapacity: 10);
        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
        private Task _consumerTask;
    
        public void Start()
        {
            // Start the background consumer task
            _consumerTask = Task.Factory.StartNew(
                () => ConsumeItemsAsync(_cts.Token),
                _cts.Token,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
        }
    
        public async Task ProduceItemAsync(int item)
        {
            await Task.Run(() => 
            {
                try
                {
                    _buffer.Add(item, _cts.Token);
                    Console.WriteLine($"Produced: {item}");
                }
                catch (OperationCanceledException)
                {
                    // Handle cancellation during add
                }
            });
        }
    
        private void ConsumeItemsAsync(CancellationToken ct)
        {
            try
            {
                foreach (var item in _buffer.GetConsumingEnumerable(ct))
                {
                    // Simulate processing time
                    Thread.Sleep(100); 
                    Console.WriteLine($"Consumed: {item}");
                }
            }
            catch (OperationCanceledException)
            {
                // Cleanup on cancellation
                Console.WriteLine("Consumer stopped");
            }
        }
    
        public async Task StopAsync()
        {
            // Signal cancellation
            _cts.Cancel();
            
            // Mark collection as complete
            _buffer.CompleteAdding();
    
            try
            {
                // Wait for consumer to finish processing
                await _consumerTask;
            }
            catch (OperationCanceledException)
            {
                // Task cancellation is expected
            }
            finally
            {
                _buffer.Dispose();
                _cts.Dispose();
            }
        }
    }
    
    // Usage example
    class Program
    {
        static async Task Main(string[] args)
        {
            var pc = new AsyncProducerConsumer();
            pc.Start();
    
            // Start multiple producers
            var producer1 = ProduceItemsAsync(pc, 1, 15);
            var producer2 = ProduceItemsAsync(pc, 16, 30);
    
            // Wait for producers to finish
            await Task.WhenAll(producer1, producer2);
    
            // Graceful shutdown
            await pc.StopAsync();
            Console.WriteLine("All tasks completed");
        }
    
        static async Task ProduceItemsAsync(AsyncProducerConsumer pc, int start, int end)
        {
            for (int i = start; i <= end; i++)
            {
                await pc.ProduceItemAsync(i);
                // Simulate variable production speed
                await Task.Delay(new Random().Next(50, 200));
            }
        }
    }
    

    Key components and features:

    1. Thread-safe Buffer: Uses BlockingCollection<int> with:

      • Bounded capacity (10 items)
      • Thread-safe operations
      • Blocking semantics when full/empty
    2. Background Consumer:

      • Created as long-running task (TaskCreationOptions.LongRunning)
      • Uses GetConsumingEnumerable() for efficient consumption
      • Processes items sequentially in background thread
    3. Async Producer API:

      • ProduceItemAsync method wraps blocking call in Task.Run
      • Supports async/await pattern for callers
      • Handles cancellation during add operations
    4. Graceful Shutdown:

      • StopAsync method coordinates shutdown:
        • Signals cancellation
        • Completes adding to collection
        • Waits for consumer to finish
        • Proper resource cleanup
      • Uses cooperative cancellation pattern
    5. Error Handling:

      • Catches OperationCanceledException for clean termination
      • Proper resource disposal in finally block
    6. Flow Control:

      • Producer blocks when buffer is full (back pressure)
      • Consumer blocks when buffer is empty
      • Bounded capacity prevents unbounded memory growth

    Usage Notes:

    • Multiple producers can add items concurrently
    • Single consumer processes items in background
    • Production rate can be faster than consumption rate (buffer handles temporary spikes)
    • Call StopAsync for graceful application shutdown
    • Random delays simulate variable processing/production times

    The pattern ensures:

    • Thread safety for shared buffer
    • Efficient resource utilization
    • Back pressure through bounded collection
    • Clean shutdown semantics
    • Async-friendly producer interface
    • Dedicated background thread for consumer

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.