您的位置:首页 > 编程语言 > C#

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。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: