Reputation: 1182
I have following code:
public void Execute(IJobExecutionContext context)
{
lock (_lockObj)
{
// ... some HTTP job that can take 5 to 30 seconds ...
}
}
When an active job is working and a second thread enters the same method, I want it locked for second thread and wait.. However, when it is already locked for a second thread, and then a 3rd thread enters the code, I want it exit the method instead of waiting and entering job execution.
I could use a static counter variable and increase/decrease its value by the thread count within job execution. But I wonder if there is already a better practice to solve this issue.
Upvotes: 1
Views: 829
Reputation: 137398
You are looking for System.Threading.Semaphore
.
var sem = new Semaphore(0, 2);
That creates a semaphore with an initial value of zero and a maximum of two. Up to two threads will be able to call sem.WaitOne()
without blocking. After that, threads that call sem.WaitOne()
will block until another thread calls sem.Release()
.
There is an overload WaitOne(int timeout)
that accepts a timeout parameter. If zero is passed for the timeout, the call will not block, and return immediately. The boolean return value indicates whether or not you successfully acquired the semaphore. In your case, if it returns False, you simply abort the operation.
Upvotes: 4