Skip SemaphoreSlim instead of waiting

I have a piece of code in an Async / Await function, and I want one thread to execute at a time.

This is relatively simple by creating a new SemaphoreSlim (1) and using WaitAsync / Release. The effect is that the first thread executes and the rest wait and then execute one after another.

What I'm trying to achieve is actually a little different. I would like other threads not to expect, but to return from a function (i.e. I don't want to block other threads). Therefore, if the "NumberOfThreadsCurrentlyExecuting" property existed, I would effectively have If Semaphore.NumberOfThreadsCurrentlyExecuting> 0 Then Return.

But such a property does not exist. Does anyone know how to solve this problem?

Thanks Charles

+4
source share
2 answers

Instead of a semaphore, you can just use Monitor.

If you call TryEnterand it fails, the other thread is in a "block".

This is a safe thread (as opposed to test semaphores) and is pretty simple:

// use somethign like: object sync = new object ();

bool lockTaken = Monitor.TryEnter(sync);
try
{
  if (lockTaken) 
  {
      // You're here - do your work
  }
  else
  {
      // Something else was in the thread - exit?
      return;
  }
}
finally
{
   if (lockTaken) Monitor.Exit(sync);
}
-1
source

Charles, what about using SemaphoreSlim.Wait/Asynca zero timeout? If it cannot enter the semaphore (since it has already been entered), it will return false.

Please note that Monitor(and therefore lock) is completely unsuitable forasync

(hence the fact that you cannot awaitc lock), because

  • , ( , ).
  • , , ( ), , ,
+9

All Articles