一:监视锁
Monitor:限定线程个数的一把锁
Monitor.Enter(b);锁住某一个资源
Monitor.Exit(b);释放某一个资源
static object lockMe = new object();
static int num = 0;
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Task.Factory.StartNew(()=> {
Run();
});
}
Console.ReadKey();
}
static void Run()
{
for (int i = 0; i < 100; i++)
{
var b = false;
try
{
Monitor.Enter(lockMe, ref b);
Console.WriteLine(num++);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (b)
{
Monitor.Exit(lockMe);
}
}
}
}
简化上面的代码:
static object lockMe = new object();
static int num = 0;
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Task.Factory.StartNew(()=> {
Run();
});
}Console.ReadKey();
}
static void Run()
{
for (int i = 0; i < 100; i++)
{
lock (lockMe)
{
Console.WriteLine(num++);
}
}
}
二:Lock/Monitor的内部机制
因为众多的锁机制中,唯独只有Monitor有专有的语法糖,所以比较重视!