这里的问题是:如果获取对象独占锁的线程(例如通过使用 Monitor.Enter)终止,是否会神奇地释放该对象的独占锁?如果那是真的,那么假设我们从另一个线程调用 Monitor.Exit - 因为我们假设对象已锁定 - 这不是会抛出 SynchronizationLockException 类型的异常吗?
我不确定这是预期的行为还是错误...
为了演示这个问题,我创建了一段简单的代码来调用 Monitor.TryEnter无需在 System.Timers.Timer.Elapsed 处调用 Monitor.Exit事件回调“请注意,Timers.Timer 类在内部使用 ThreadPool 来运行回调事件处理程序,并且它可能每次都调用经过的回调在与池不同的线程上。”
class Foo
{
private System.Timers.Timer _timer = new System.Timers.Timer(2000);//every 2s
private static readonly object _locker = new object();//static locker object
public Foo()
{
_timer.Elapsed += delegate
{
if (Monitor.TryEnter(_locker))//acquiring the lock without calling Exit..
{
Console.WriteLine(string.Format("Access Succeed!!, Thread Id {0}",
Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(6000);//simulate a work for 6 seconds
}
else
{
Console.WriteLine(string.Format("Unable to access to locker method within locker object, Thread Id {0}",
Thread.CurrentThread.ManagedThreadId));
}
};
_timer.Start();
}
}
//to test: just initialize a new instance of foo class
Foo foo = new Foo();
//blocks until application is terminated..
Thread.Sleep(Timeout.Infinite);
输出窗口显示的结果:
Access Succeed!!, Thread Id 11
Unable to access to locker method within locker object, Thread Id 12
Unable to access to locker method within locker object, Thread Id 12
Access Succeed!!, Thread Id 11
Unable to access to locker method within locker object, Thread Id 12
Unable to access to locker method within locker object, Thread Id 12
Unable to access to locker method within locker object, Thread Id 12
Unable to access to locker method within locker object, Thread Id 12
Access Succeed!!, Thread Id 11
Unable to access to locker method within locker object, Thread Id 12
Unable to access to locker method within locker object, Thread Id 12
....
请您参考如下方法:
这里没有线程被终止。
相反,它们返回到线程池,仅供以后的计时器事件重用。
Monitor.Enter 是可重入的;在同一个线程上两次进入锁不会阻塞。
