using System.Collections.Concurrent;
using System.Threading.Tasks;
class ProgramWithCancellation
var cts = new CancellationTokenSource();
var numberCollection = new BlockingCollection<int>(10);
Task t1 = Task.Run(() => NonBlockingConsumer(numberCollection, cts.Token));
Task t2 = Task.Run(() => NonBlockingProducer(numberCollection, cts.Token));
Console.WriteLine("exit.");
static void NonBlockingConsumer(BlockingCollection<int> bc, CancellationToken ct)
if (!bc.TryTake(out nextItem, 0, ct))
Console.WriteLine("Take Blocked:{0}", nextItem);
Console.WriteLine("Take:{0}", nextItem);
catch (OperationCanceledException)
Console.WriteLine("Taking canceled.");
Console.WriteLine("No more items to take.");
static void NonBlockingProducer(BlockingCollection<int> bc, CancellationToken ct)
success = bc.TryAdd(itemToAdd, 2, ct);
catch (OperationCanceledException)
Console.WriteLine("Add loop canceled.");
Console.WriteLine("Add:{0}", itemToAdd);
Console.Write("AddBlocked:{0} Count = {1}", itemToAdd.ToString(), bc.Count);
UpdateProgress(itemToAdd);
} while (itemToAdd < inputs);
static void UpdateProgress(int i)
double percent = ((double)i / inputs) * 100;
Console.WriteLine(" Percent complete: {0}", percent);