Interlocked 是线程安全的原子操作该怎么用这个类下面的方法 将bool型的变量赋值为 true ?

解决方案 »

  1.   

    http://msdn.microsoft.com/zh-cn/library/system.threading.interlocked.aspx
      

  2.   

    http://cxy.uueasy.com/simple/?t607.html       ------》》
      

  3.   

    Exchange<T>(T, T)
    //A simple method that denies reentrancy.
            static void UseResource()
            {
                //0 indicates that the method is not in use.
                if(false == Interlocked.Exchange<bool>(bool, true)) //用这个可以完成你要的赋值操作。
                {
                    Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);                //Code to access a resource that is not thread safe would go here.                //Simulate some work
                    Thread.Sleep(500);                Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name);                //Release the lock                
                }
            }
      

  4.   


    你自己转换一下吧,0代表false,非0代表true
      

  5.   

    Interlocked.Exchange<bool>(bool, true)写错了,应该是
    Interlocked.Exchange<bool>(boolVar, true)//boolVar你要改变的变量名
      

  6.   

    5楼的代码不对.提示 必须是引用类型才能作为参数.Interlocked.Exchange<bool>(boolVar, true);Interlocked.Exchange<bool>(ref boolVar, true)//上面两种都不行
      

  7.   

    经过自己的试验,发现上面我的方法Interlocked.Exchange<T>(T, T)不对,因为泛型类T必须是引用类型,而bool是struct,为值类型,非引用类型!,见定义:
    public static T Exchange<T>(ref T location1,T value) where T : class
    所以只能用下面的方法:        static void SetValue()
            {
                object status = true;
                System.Threading.Interlocked.Exchange(ref status, (object)true);
            }
      

  8.   

    也就是System.Threading.Interlocked.Exchange(ref Object,Object)方法来完成。