这样可以确保该字段在任何时间呈现的都是最新的值。
lock 语句对访问进行序列化的字段。
volatile 关键字可应用于以下类型的字段:
-
引用类型。
-
换句话说,您无法声明“指向可变对象的指针”。
-
类型,如 sbyte、byte、short、ushort、int、uint、char、float 和 bool。
-
具有以下基类型之一的枚举类型:byte、sbyte、short、ushort、int 或 uint。
-
已知为引用类型的泛型类型参数。
-
UIntPtr。
volatile。
线程处理(C# 和 Visual Basic)。
using System;
using System.Threading;
namespace WorkerThreadExample
{
class Program
{
static void Main(string[] args)
{
// Create the worker thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
// Start the worker thread.
workerThread.Start();
Console.WriteLine("Main thread: starting worker thread...");
// Loop until the worker thread activates.
while (!workerThread.IsAlive) ;
// Put the main thread to sleep for 1 millisecond to
// allow the worker thread to do some work.
Thread.Sleep(1);
// Request that the worker thread stop itself.
workerObject.RequestStop();
// Use the Thread.Join method to block the current thread
// until the object's thread terminates.
workerThread.Join();
Console.WriteLine("Main thread: worker thread has terminated.");
}
// Sample output:
// Main thread: starting worker thread...
// Worker thread: working...
// Worker thread: working...
// Worker thread: working...
// Worker thread: working...
// Worker thread: working...
// Worker thread: working...
// Worker thread: terminating gracefully.
// Main thread: worker thread has terminated.
}
public class Worker
{
// This method is called when the thread is started.
public void DoWork()
{
while (!_shouldStop)
{
Console.WriteLine("Worker thread: working...");
}
Console.WriteLine("Worker thread: terminating gracefully.");
}
public void RequestStop()
{
_shouldStop = true;
}
// Keyword volatile is used as a hint to the compiler that this data
// member is accessed by multiple threads.
private volatile bool _shouldStop;
}
}
参考 MSDN http://msdn.microsoft.com/zh-cn/library/x13ttww7.aspx
谢谢浏览!