Lock关键字
C#提供lock关键字实现临界区,MSDN里给出的用法:
Object thisLock = new Object();
lock (thisLock)
{
// Critical code section
}
还有一种是比lock更“高级”的Monitor:
private static object obj = new object(); public static void SomeMethod() { bool lockTaken=false; //假定没有获取锁 try { //无论是否抛出异常下面代码都正常运行 Monitor.Enter(obj, ref lockTaken); //执行线程安全的操作... } catch (Exception ex) { //异常捕获 } finally { //如果已获锁就释放 if (lockTaken) Monitor.Wait(obj); } }