|
(一).描述 此示例演示分别用lock以及Interlicked和Monitor类实现线程的临界区操作(互斥) (二).代码 using System; using System.Threading; using System.Collections; namespace 加锁_实现临界区互斥操作_ { //委托声明(函数签名) delegate string MyMethodDelegate(); class MyClass { private static ArrayList arrList = new ArrayList(); private static int i = 0; public static void Add() { //方法一:用 lock 实现 // lock(arrList) // { // arrList.Add(i.ToString()); // i++; // } //方法二: 用Interlicked类实现 // System.Threading.Interlocked.Increment(ref i); // arrList.Add(i.ToString()); //方法三: 用Monitor类实现 try { //I.不限时间 //stem.Threading.Monitor.Enter(arrList); //II.在指定时间获得排他锁 if(System.Threading.Monitor.TryEnter(arrList,TimeSpan.FromSeconds(30))) //在30秒内获取对象排他锁. 灵活运用可以实现防止死锁功能 {   [1] [2] [3] 下一页
|