From the course: Threading in C#

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Monitor and locks

Monitor and locks - C# Tutorial

From the course: Threading in C#

Start my 1-month free trial

Monitor and locks

- [Instructor] Lets take a look at a real world example where we must use locks otherwise we can have unintended consequences of the code we write. In this example I'd like to show you locks as well as how we can use locks using Monitor.Enter and Exit. The problem statement is simple. We'd like to have an Account class and we will like to withdraw a certain amount of random amounts from the Account class. And at some point of time, if our balance is less than zero, we would want to make sure that we do not allow that, as well as, throw an exception. If you right-click on your project and create a class. Call it Account. We can create an internal class in this case. Feel free to create a public one if you like. If you type c t o r and hit Tab, it will automatically generate a constructor for you. I think the first thing I like to add is going to be the initial amount. So this is more like the initial balance for the most part or we can even just call it initialBalance. Once I have the…

Contents