gpt4 book ai didi

c# - 在计时器经过回调时调用没有 Monitor.Exit 的 Monitor.TryEnter 显示意外行为

转载 作者:太空宇宙 更新时间:2023-11-03 22:01:38 28 4
gpt4 key购买 nike

这里的问题是:如果获取对象独占锁的线程(例如通过使用 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 是可重入的;在同一个线程上两次进入锁不会阻塞。

关于c# - 在计时器经过回调时调用没有 Monitor.Exit 的 Monitor.TryEnter 显示意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9877218/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com