C#线程安全使用(三)
2013-10-21 15:46
225 查看
在讲CancellationTokenSource之前我决定先讲一下lock和Interlocked,如果能很好的理解这两个,再去理解CancellationTokenSource就会方便很多,由于我也是后起使用多线程,使用的时候就是直接运用FramWork4的东西,这样导致了很多东西学起来很吃力,当回顾了以前的知识点后,发现新出的东西如此好理解。
先看一下Lock的使用,下面是一个例子。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MyInterlockedExchangeExampleClass { class MyInterlockedExchangeExampleClass { //0 for false, 1 for true. private static int usingResource = 0; private const int numThreadIterations = 5; private const int numThreads = 10; static void Main() { Thread myThread; Random rnd = new Random(); for (int i = 0; i < numThreads; i++) { myThread = new Thread(new ThreadStart(MyThreadProc)); myThread.Name = String.Format("Thread{0}", i + 1); //Wait a random amount of time before starting next thread. Thread.Sleep(rnd.Next(0, 1000)); myThread.Start(); } } private static void MyThreadProc() { for (int i = 0; i < numThreadIterations; i++) { UseResource(); //Wait 1 second before next attempt. Thread.Sleep(1000); } } //A simple method that denies reentrancy. static bool UseResource() { //0 indicates that the method is not in use. //原始值是0,判断是时候使用原始值,但判断后值为1,进行了设置 if (0 == Interlocked.Exchange(ref usingResource, 1)) { Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name); //Code to access a resource that is not thread safe would go here. //Simulate some work Thread.Sleep(500); Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name); //Release the lock Interlocked.Exchange(ref usingResource, 0); return true; } else { Console.WriteLine(" {0} was denied the lock", Thread.CurrentThread.Name); return false; } } } }View Code
理解了lock和interlock后下一章讲解CancellationTokenSource。
相关文章推荐
- C#中把当前显示的datagridview中的数据以excel的形式导出
- 描述C#多线程中 lock关键字
- C#之相等比较
- C#中各种计时器
- C#设计模式学习资料--装饰模式
- [C#]AES加密算法实现
- C# 调用外部程序Process类
- C# 实现的多线程异步Socket数据包接收器框架
- C#读取XML(全部或根据某个节点的属性值)
- C# 日期相减得到分钟数、小时、天数
- C#设计模式学习资料--外观模式
- C# 常用正则表达式
- C# overload、override、hiding区别
- C#下类中 访问窗体控件的问题
- c# 读取opencv 生成的svm训练好的xml分类器
- C# 一个页面,多个Updatepannel,多个Timer
- C#泛型列表List<T>基本用法总结
- c# 常见错误
- C# List与DataTable的相互转化
- c#总结笔记