Monitor主要方法TryEnter、Enter、Exit
lock关键字基于Monitor.Enter,Monitor.Exit 实现
static void Main(string[] args)
{
for (int j = 0; j < 10; j++)
{
int k = j;
Task.Run(() =>
{
Show(k);
});
}
Console.ReadKey();
}
private static readonly object obj = new object();
private static void Show(int num)
{
bool lockTaken = false;//是否获得了该锁
//Monitor.TryEnter(obj, 2000, ref lockTaken);//等待锁时间,超过2000毫秒就不在等待获取锁
Monitor.TryEnter(obj, -1, ref lockTaken);//获取锁,等同于Monitor.Enter(obj)
/* TryEnter不阻塞线程,不会造成死锁,Enter会阻塞,可能造成死锁 */
if (lockTaken)
{
Console.WriteLine($"{DateTime.Now}");
try
{
Console.WriteLine($"{num} 开始");
Thread.Sleep(1100);
Console.WriteLine($"{num} 结束");
}
finally
{
Monitor.Exit(obj);//释放锁
}
}
else
{
}
}