1 class Program 2 { 3 static BlockingCollection<int> cols = new BlockingCollection<int>(2); //设置阻塞队列最大的容量; 4 public static void Main(string[] args) 5 { 6 7 8 var t1 = Task.Factory.StartNew(product); 9 10 Thread.Sleep(50); 11 t1.Wait(); 12 Task.Factory.StartNew(consumer); 13 14 15 16 Console.ReadKey(true); 17 } 18 public static void product(){ 19 20 for (int i = 0; i < 2; i++) { 21 22 cols.Add(i); 23 Console.WriteLine("i`m producter set value{0}", i); 24 } 25 26 Console.WriteLine("all item has add..."); 27 //cols.CompleteAdding(); //设置完成标志位,否则 IsAddingCompleted一直是true 28 29 } 30 31 public static void consumer(){ 32 33 34 while (!cols.IsAddingCompleted) { 35 36 37 Console.WriteLine("take function is 阻塞的么?"); 38 int item; 39 bool finish = cols.TryTake(out item, TimeSpan.FromSeconds(5));// try可以加阻塞时间,超时则停止取值; 40 41 if(finish){ 42 43 Console.WriteLine("i`m consumer get value {0}", item); 44 } 45 46 } 47 48 Console.WriteLine("all item has get..."); 49 } 50 }