Sunday, November 27, 2011

lock Statement (C# Reference)

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. The following example includes a lock statement.
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
As long as the lock statement is present, the statement block is a critical section and balance will never become a negative number. See the following example.

//Account.cs
class Account
{
     decimal balance;
     private Object thisLock = new Object();

     public void Withdraw(decimal amount)
     {
          lock (thisLock)
          {
               if (amount > balance)
               {
                    throw new Exception("Insufficient funds");
               }
               balance -= amount;
          }
     }
}

1 comment:

  1. Exactly what i was looking for and the lock statement helped me! Sample Statements

    ReplyDelete