Is there a construct similar to locking in C # that skips a block of code rather than blocking?

In the part of the code I'm working on, another developer library runs one of my object methods at regular, scheduled intervals. I ran into problems when the previous call to the method of the object did not end at the moment when another interval was reached, and the second call was made to my method to execute again - these two threads then switch to each other. I would like to be able to wrap the method implementation with a check to see if it is in the middle of processing and skip the block, if so.

The lock is similar to what I want, but does not completely cover it, because the lock is blocked, and the call to my method will be raised as soon as the previous instance releases the lock. This is not what I want, because I could end up with a large number of these calls, and everyone is waiting for the process one at a time. Instead, I would like something similar to a lock, but without a block, so that execution continues after a block of code that would normally be surrounded by a lock.

I developed a counter that will be used with Interlocked.Increment and Interlocked.Decrement to allow me to use a simple if statement to determine if this method should continue to run.

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);
    }
}

It seems to me that I overdid it, and there might be a simpler solution.

+3
source
3

Monitor.TryEnter , false.

+7
public class Processor
{
    private readonly object lockObject = new object();

    public void PerformProcessing()
    {
        if (Monitor.TryEnter(lockObject) == true)
        {
            try
            {
                // Do something...
            }
            finally
            {
                Monitor.Exit(lockObject);
            }
        }
    }
}
+3

How to add a flag to an object. The method has the true flag set, indicating that the method is executing. At the very end of the reset method, this value is false. You can then check the status of the flag to see if this method can be called.

0
source

Source: https://habr.com/ru/post/1795285/


All Articles