C# 线程同步
2013-10-13 23:21
375 查看
using System; using System.Threading; using System.Text; using System.Threading.Tasks; //多线程调试: 2013.10.08 //转自 http://www.cnblogs.com/yank/p/3227324.html namespace ThreadExample { class SpinLockSample { public static void Test() { SpinLock sLock = new SpinLock(); StringBuilder sb = new StringBuilder(); Action action = () => { bool gotLock = false; for (int i = 0; i < 5; i++) { gotLock = false; try { sLock.Enter(ref gotLock); sb.Append(i.ToString()); } catch (System.Exception ex) { } finally { if (gotLock) { sLock.Exit(); } } } }; //多线程调用action Parallel.Invoke(action,action,action); Console.WriteLine("Ouput {0}",sb.ToString()); } } class App { private static object UsingPrinterLocker = new object(); private static Mutex mutex = new Mutex(); public static void Main() { SpinLockSample.Test(); //TestPrint(); } public static void TestPrint() { Thread thread; Random random = new Random(); for (int i = 0; i < 10;i++ ) { thread = new Thread(MyThreadProc); thread.Name = string.Format("Thread {0}", i); Thread.Sleep(random.Next(3)); thread.Start(); } } public static void MyThreadProc() { //UserPrinter(); //UsePrinterWithMutex(); UsePrinterWithMoniter(); } public static void UsePrinterWithMutex() { mutex.WaitOne(); try { Console.WriteLine("{0} acquired thd lock", Thread.CurrentThread.Name); Thread.Sleep(2000); Console.WriteLine("{0} exiting lock.", Thread.CurrentThread.Name); } catch (System.Exception ex) { } finally { mutex.ReleaseMutex(); } } public static void UsePrinterWithMoniter() { System.Threading.Monitor.Enter(UsingPrinterLocker); try { Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name); Thread.Sleep(500); Console.WriteLine("{0} exit lock", Thread.CurrentThread.Name); } catch (System.Exception ex) { } finally { System.Threading.Monitor.Exit(UsingPrinterLocker); } } public static void UserPrinter() { lock (UsingPrinterLocker) { Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name); Thread.Sleep(500); Console.WriteLine("{0} exiting lock.", Thread.CurrentThread.Name); } } } }
相关文章推荐
- c#学习系列之字段(静态,常量,只读)
- C# 实现Ajax的方式总结
- c# 获取远程用户ip,z真实ip
- 【转】C#中没有id 没有name C#怎么点击按钮
- 用C#绘图
- C#实现窗体间的通信
- 当Reshaper快捷键失效时
- C#+AE要素的操作,添加、更新和删除要素
- C#+AE不同shp文件要素的复制
- C# DataTable,DataSet,IList,IEnumerable 互转扩展属性
- C# DataTable,DataSet,IList,IEnumerable 互转扩展属性
- C#计算时间间隔的方法小结
- C#
- 深入理解C# 3.x的新特性
- C#语言中如何使用Point 类型数组
- C#Windows窗体界面设计_01_绘制三角函数_五点作图法
- C#Windows窗体界面设计_01_绘制三角函数_附强制类型转换
- Make Yahoo! Web Service REST Calls With C#
- C# 将2进制转化为单精度的方法
- C# Lambda表达式