C#中的并发集合Concurrent类

  internal static BlockingCollection _TestBCollection;

  class ThreadWork1 // 生产者

  {

  public ThreadWork1()

  { }

  public void run()

  {

  System.Console.WriteLine("ThreadWork1 run { ");

  for (int i = 0; i < 100; i++)

  {

  System.Console.WriteLine("ThreadWork1 producer: " + i);

  _TestBCollection.Add(i);

  }

  _TestBCollection.CompleteAdding();

  System.Console.WriteLine("ThreadWork1 run } ");

  }

  }

  class ThreadWork2 // 消费者

  {

  public ThreadWork2()

  { }

  public void run()

  {

  int i = 0;

  int nCnt = 0;

  bool IsDequeuue = false;

  System.Console.WriteLine("ThreadWork2 run { ");

  while (!_TestBCollection.IsCompleted)

  {

  IsDequeuue = _TestBCollection.TryTake(out i);

  if (IsDequeuue)

  {

  System.Console.WriteLine("ThreadWork2 consumer: " + i * i + " =====" + i);

  nCnt++;

  }

  }

  System.Console.WriteLine("ThreadWork2 run } ");

  }

  }

  static void StartT1()

  {

  ThreadWork1 work1 = new ThreadWork1();

  work1.run();

  }

  static void StartT2()

  {

  ThreadWork2 work2 = new ThreadWork2();

  work2.run();

  }

  static void Main(string[] args)

  {

  Task t1 = new Task(() => StartT1());

  Task t2 = new Task(() => StartT2());

  _TestBCollection = new BlockingCollection();//可以跟容量

  Console.WriteLine("Sample 4-4 Main {");

  Console.WriteLine("Main t1 t2 started {");

  t1.Start();

  t2.Start();

  Console.WriteLine("Main t1 t2 started }");

  Console.WriteLine("Main wait t1 t2 end {");

  Task.WaitAll(t1, t2);

  Console.WriteLine("Main wait t1 t2 end }");

  Console.WriteLine("Sample 4-4 Main }");

  }