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 } }
经过自己的试验,发现上面我的方法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); }
//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
}
}
你自己转换一下吧,0代表false,非0代表true
Interlocked.Exchange<bool>(boolVar, true)//boolVar你要改变的变量名
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);
}