在事件处理程序方法中使用 Monitor.TryEnter 可以吗?
我有 EventHandler 方法,该方法经常被调用,并且它的主体处理需要一些时间。通过监视器锁定此处理程序内的操作可以吗? 目的是在locker锁定对象的同时,简单地跳过对象的其他事件和处理。
public void MyEventHandler(object sender, EventArgs e)
{
if (!Monitor.TryEnter(locker)) return; // skipping meanwhile processing
// do some stuff here
Monitor.Exit(locker)
}
I have EventHandler method which is called pretty often and it's body processing takes some time. Is it OK, to lock operations inside this handler it via Monitor?
The purpose is that meanwhile locker locks the object other events and processing of the object are simply skipped.
public void MyEventHandler(object sender, EventArgs e)
{
if (!Monitor.TryEnter(locker)) return; // skipping meanwhile processing
// do some stuff here
Monitor.Exit(locker)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来
无论如何,始终将 Monitor.Exit 放入 finally 块中
it looks like it would be cleaner/more performant to
Regardless, always put the Monitor.Exit into a finally block
这并不可怕,只要:
//do some stuff
代码所需的所有访问。TryEnter
之后的所有内容包装在try
/finally
中,如下所示:
(从而避免启动一个线程可能不执行任何操作 - 当然因为您没有在事件处理线程上进行这种耗时的处理...)
如果您可以完全阻止触发事件,那就更好了 ,如果您实际上不需要在整个持续时间内锁定(也就是说,如果事件处理程序不会执行任何需要与其他代码同步的操作),您可以锁定足够长的时间设置一个标志,例如
It's not horrible, as long as:
//do some stuff
code needs.TryEnter
in atry
/finally
, like so:.
It'd be nicer if you could prevent firing the event at all (and thus avoid starting a thread to potentially do nothing -- cause of course you're not doing this time-consuming processing on the event handling thread...)
Alternatively, if you don't really need to lock for the whole duration (that is, if the event handler won't be doing anything that requires synchronization with other code), you could lock just long enough to set a flag, like