I want to start some new threads each for one repeating operation. But when such an operation is already in progress, I want to discard the current task. In my scenario I need very current data only – dropped data is not an issue.
In the MSDN I found the Mutex class but as I understand it, it waits for its turn, blocking the current thread. Also I want to ask you: Does something exist in the .NET framework already, that does the following:
- Is some method M already being executed?
- If so,
return(and let me increase some counter for statistics) - If not, start method M in a new thread
The
lock(someObject)statement, which you may have come across, is syntactic sugar aroundMonitor.EnterandMonitor.Exit.However, if you use the monitor in this more verbose way, you can also use
Monitor.TryEnterwhich allows you to check if you’ll be able to get the lock – hence checking if someone else already has it and is executing code.So instead of this:
try this (option 1):
(you’ll probably want to put a try..finally in there to ensure the lock is released)
or dispense with the explicit lock althogether and do this
(option 2)
[Edit: in response to your question about
this]No – don’t use
thistolockon. Create a privately scoped object to act as your lock.Otherwise you have this potential problem:
In the above example, some external code has managed to disrupt the internal locking of our class just by taking out a lock on something that was externally accessible.
Much better to create a private object that you control, and that no-one outside your class has access to, to avoid these sort of problems; this includes not using
thisor the type itselftypeof(MyClassWithLockInside)for locking.