日期:2014-05-18  浏览次数:20863 次

请大家来帮我讨论一下,这个MSDN示例---Interlocked
using System;
using System.Threading;

class Test
{
  static void Main()
  {
  Thread thread1 = new Thread(new ThreadStart(ThreadMethod));
  Thread thread2 = new Thread(new ThreadStart(ThreadMethod));
  thread1.Start();
  thread2.Start();
  thread1.Join();
  thread2.Join();

  // Have the garbage collector run the finalizer for each
  // instance of CountClass and wait for it to finish.
  GC.Collect();
  GC.WaitForPendingFinalizers();

  Console.WriteLine("UnsafeInstanceCount: {0}" +
  "\nSafeCountInstances: {1}",
  CountClass.UnsafeInstanceCount.ToString(),
  CountClass.SafeInstanceCount.ToString());
  }

  static void ThreadMethod()
  {
  CountClass cClass;

  // Create 100,000 instances of CountClass.
  for(int i = 0; i < 100000; i++)
  {
  cClass = new CountClass();
  }
  }
}

class CountClass
{
  static int unsafeInstanceCount = 0;
  static int safeInstanceCount = 0;

  static public int UnsafeInstanceCount
  {
  get {return unsafeInstanceCount;}
  }

  static public int SafeInstanceCount
  {
  get {return safeInstanceCount;}
  }

  public CountClass()
  {
  unsafeInstanceCount++;
  Interlocked.Increment(ref safeInstanceCount);
  }

  ~CountClass()
  {
  unsafeInstanceCount--;
  Interlocked.Decrement(ref safeInstanceCount);
  }
}

创建时公共资源增加1,析构时公共int资源safeInstanceCount减少1,
与之对比的是不通过的Interlocked进行这种成对增减的 unsafeInstanceCount变量,
//===
我测试的结果上看它们是一样的值都是0

大家有没有什么见解,说明一下为什么是这样的结果,谢谢!

------解决方案--------------------
结贴吧哥们