I have a method which should be executed in an exclusive fashion. Basically, it’s a multi threaded application where the method is invoked periodically by a timer, but which could also be manually triggered by a user action.
Let’s take an example :
-
The timer elapses, so the method is called. The task could take a few seconds.
-
Right after, the user clicks on some button, which should trigger the same task : BAM. It does nothing since the method is already running.
I used the following solution :
public void DoRecurentJob() { if(!Monitor.TryEnter(this.lockObject)) { return; } try { // Do work } finally { Monitor.Exit(this.lockObject); } }
Where lockObject is declared like that:
private readonly object lockObject = new object();
Edit : There will be only one instance of the object which holds this method, so I updated the lock object to be non-static.
Is there a better way to do that ? Or maybe this one is just wrong for any reason ?
This looks reasonable if you are just interested in not having the method run in parallel. There’s nothing to stop it from running immediately after each other, say that you pushed the button half a microsecond after the timer executed the Monitor.Exit().
And having the lock object as readonly static also make sense.