private static void UsingConcurrentStack() { var sharedCollection = new ConcurrentStack <int>(); for (int i = 0; i < 1000; i++) { sharedCollection.Push(i); } int itemCount = 0; var tasks = new Task[10]; for (int i = 0; i < tasks.Length; i++) { tasks[i] = new Task(() => { while (sharedCollection.Count > 0) { int item; bool isItemGot = sharedCollection.TryPop(out item); if (isItemGot) { Interlocked.Increment(ref itemCount); } } }); tasks[i].Start(); } Task.WaitAll(tasks); Console.WriteLine($"Items of {sharedCollection.GetType()} processed: {itemCount}"); }