System.Threading.Interlocked类为多个线程共享的变量提供原子操作。
为整型类提供原子类操作
经验显示,那些需要在多线程情况下被保护的资源通常是整型值,且这些整型值在多线程下最常见的操作就是递增、递减或相加操作。Interlocked类提供了一个专门的机制用于完成这些特定的操作。这个类提供了Increment、Decrement、Add静态方法用于对int或long型变量的递增、递减或相加操作。
示例代码:
using System;
using System.Threading;
namespace ProcessTest
{
class Program
{
staticint counter =1;
staticvoid Main(string[] args)
{
Thread t1 =new Thread(new ThreadStart(F1));
Thread t2 =new Thread(new ThreadStart(F2));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
System.Console.ReadKey();
}
staticvoid F1()
{
for (int i =0; i <5; i++)
{
Interlocked.Increment(ref counter);
System.Console.WriteLine("Counter++ {0}", counter);
Thread.Sleep(10);
}
}
staticvoid F2()
{
for (int i =0; i <5; i++)
{
Interlocked.Decrement(ref counter);
System.Console.WriteLine("Counter-- {0}", counter);
Thread.Sleep(10);
}
}
}
}
using System.Threading;
namespace ProcessTest
{
class Program
{
staticint counter =1;
staticvoid Main(string[] args)
{
Thread t1 =new Thread(new ThreadStart(F1));
Thread t2 =new Thread(new ThreadStart(F2));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
System.Console.ReadKey();
}
staticvoid F1()
{
for (int i =0; i <5; i++)
{
Interlocked.Increment(ref counter);
System.Console.WriteLine("Counter++ {0}", counter);
Thread.Sleep(10);
}
}
staticvoid F2()
{
for (int i =0; i <5; i++)
{
Interlocked.Decrement(ref counter);
System.Console.WriteLine("Counter-- {0}", counter);
Thread.Sleep(10);
}
}
}
}
Interlocked类还提供了Exchange(为整型或引用对象赋值)、CompareExchange(比较后再对整型或引用对象赋值),用于为整型或引用类型的赋值提供原子操作。