0

I feel that I have a good grasp on how Wait and WaitAsync work. I understand that Wait() will block the thread while it waits for the Semaphore to become available. On the other hand WaitAsync() will return that thread to the thread pool so it may continue to be used while waiting for the Semaphore.

I'm hoping someone can explain under what conditions would you choose Wait() over WaitAsync()? Is it advantageous in certain situations to make absolutely sure that the code continues executing on the same thread by calling Wait()? I can't seem to find any good reason to use the Wait() method as this just blocks the thread which looks to me to be a waste of resources.

Quoting another poster replying to a similar question https://stackoverflow.com/a/44306177/13274736: "If you have async method - you want to avoid any blocking calls if possible. SemaphoreSlim.Wait() is a blocking call. So what will happen if you use Wait() and semaphore is not available at the moment? It will block the caller, which is very unexpected thing for async methods"

Why would we want to avoid blocking calls and why would this be unexpected for async methods?

Thank you for any help!

  • 2
    Why do you think `SemaphoreSlim` can only be used in `async` methods? It seems pretty straightforward to me: Is the method `async`? Yes -> `WaitAsync`, No -> `Wait` –  Apr 10 '20 at 02:18
  • You may want to create an application very focused at performing a specific operation. Such an application could create a fixed (small) number of threads at start up, and run on these initially created threads throughout its lifetime. In this scenario adding asynchrony to the mix could result to pure overhead without any benefit, in which case `Wait` would be preferable to `WaitAsync`. – Theodor Zoulias Apr 10 '20 at 02:50
  • @Knoop, that is a valid point and I don't necessarily think that SemaphoreSlim can only be used in async methods. However, I'm still trying to understand what (if any) danger exists as a result of using 'Wait' in an 'async' method. – Austin Yount Apr 10 '20 at 20:15
  • 1
    @TheodorZoulias, The point about added overhead relating to asynchrony makes sense. – Austin Yount Apr 10 '20 at 20:21
  • In general if a library provides you with both an async and non-async version of the same method, don't use the non-async one in your async code. My point was that `SemaphoreSlim` can be used both in async and non-async code and therefor provides the appropriate methods for both. So the whole "yeah but isn't the non-async version bad in async code?" feels a bit weird to me. But maybe the question you really wanted to know was "Does Wait block if called from an async method?" in that case the answer is: yes. –  Apr 11 '20 at 06:51

0 Answers0