Is there a construct similar to a lock in C# that skips over a block of code rather than blocking?
In the piece of code that I'm working on, another developer's library fires off one of my object's methods on regular, scheduled intervals. I've run into problems where the previous call into my object's metho开发者_Go百科d has not completed at the time another interval is reached and a second call is made into my method to execute again - the two threads then end up stepping on each other. I'd like to be able to wrap the method's implementation with a check to see whether it is in the middle of processing and skip over the block if so.
A lock is similar to what I want, but doesn't quite cover it because a lock will block and the call into my method will pick up as soon as the previous instance releases the lock. That's not what I want to happen because I could potentially end up with a large number of these calls backed up and all waiting to process one by one. Instead, I'd like something similar to a lock, but without the block so that execution will continue after the block of code that would normally be surrounded by the lock.
What I came up with was a counter to be used with Interlocked.Increment and Interlocked.Decrement to allow me to use a simple if statement to determine whether execution on the method should continue.
public class Processor
{
private long _numberOfThreadsRunning = 0;
public void PerformProcessing()
{
long currentThreadNumber Interlocked.Increment(ref _numberOfThreadsRunning);
if(currentThreadNumber == 1)
{
// Do something...
}
Interlocked.Decrement(ref _numberOfThreadsRunning);
}
}
I feel like I'm overthinking this and there may be a simpler solution out there.
You could call Monitor.TryEnter
and just continue if it returns false.
public class Processor
{
private readonly object lockObject = new object();
public void PerformProcessing()
{
if (Monitor.TryEnter(lockObject) == true)
{
try
{
// Do something...
}
finally
{
Monitor.Exit(lockObject);
}
}
}
}
How about adding a flag to the object. In the method set the flag true to indicated the method is being executed. At the very end of the method, reset it to false. Then you could check the status of the flag to know if the method can be called.
精彩评论