Is it OK to use Monitor.TryEnter in event handler method?
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; // ski开发者_JS百科pping meanwhile processing
// do some stuff here
Monitor.Exit(locker)
}
it looks like it would be cleaner/more performant to
- (a) prevent the events from being raised
- (b) use a condition variable.
Regardless, always put the Monitor.Exit into a finally block
It's not horrible, as long as:
- You're doing this on a background thread (or, to the point, you're not doing this on the event handling thread).
- You're synchronizing all access to whatever your
//do some stuff
code needs. - You wrap everything after the
TryEnter
in atry
/finally
, like so:
.
public void MyEventHandler(object sender, EventArgs e)
{
if (!Monitor.TryEnter(locker)) return;
try
{
// do some stuff here
}
finally
{
Monitor.Exit(locker);
}
}
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
private Object condition_lock = new Object();
private bool handlingEvent = false;
public void MyEventHandler(object sender, EventArgs e)
{
lock (condition_lock)
{
if (handlingEvent) return;
handlingEvent = true;
}
try
{
// do some stuff here
}
finally
{
handlingEvent = false;
}
}
精彩评论