System.Threading.Interlocked类为多个线程共享的变量提供原子操作。
为整型类提供原子类操作
经验显示,那些需要在多线程情况下被保护的资源通常是整型值,且这些整型值在多线程下最常见的操作就是递增、递减或相加操作。Interlocked类提供了一个专门的机制用于完成这些特定的操作。这个类提供了Increment、Decrement、Add静态方法用于对int或long型变量的递增、递减或相加操作。
示例代码:
using
System;
using System.Threading;
namespace ProcessTest
{
class Program
{
static int counter = 1 ;
static void 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();
}
static void F1()
{
for ( int i = 0 ; i < 5 ; i ++ )
{
Interlocked.Increment( ref counter);
System.Console.WriteLine( " Counter++ {0} " , counter);
Thread.Sleep( 10 );
}
}
static void 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
{
static int counter = 1 ;
static void 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();
}
static void F1()
{
for ( int i = 0 ; i < 5 ; i ++ )
{
Interlocked.Increment( ref counter);
System.Console.WriteLine( " Counter++ {0} " , counter);
Thread.Sleep( 10 );
}
}
static void F2()
{
for ( int i = 0 ; i < 5 ; i ++ )
{
Interlocked.Decrement( ref counter);
System.Console.WriteLine( " Counter-- {0} " , counter);
Thread.Sleep( 10 );
}
}
}
}