Understanding locks, semaphores, and SemaphoreSlim
In the previous sections, we saw how we can use various APIs in .NET to achieve parallelism. However, when we are doing that, we need to take additional care with shared variables. Let's take the enterprise e-commerce application that we are building in this book. Think about the workflow of purchasing an item. Say that two users are planning to buy a product and only one item is available. Let's say that both users add the item to the cart and user 1 places their order, and while the order is being processed through the payment gateway, user 2 also tries to place their order.
In such cases, the second order should fail (assuming that the first order succeeded), because the quantity for the book is now 0; that would happen only if there was proper synchronization being applied to the quantity across threads. Also, if the first order fails in the payment gateway or user 1 cancels their transaction, the second order should...