Mega Code Archive

 
Categories / C# / Collections Data Structure
 

ConcurrentBag represents a thread-safe, unordered collection of objects

using System; using System.Collections.Concurrent; class ConcurrentBagDemo {     static void Main()     {         ConcurrentBag<int> cb = new ConcurrentBag<int>();         cb.Add(1);         cb.Add(2);         cb.Add(3);         int item;         while (!cb.IsEmpty)         {             if (cb.TryTake(out item))                 Console.WriteLine(item);             else                 Console.WriteLine("TryTake failed for non-empty bag");         }         if (cb.TryPeek(out item))             Console.WriteLine("TryPeek succeeded for empty bag!");     } }