The lock keyword marks a statement block as a critical section.
lock(expression) statement_block
where:
Typically, expression will either be this, if you want to protect an instance variable, or typeof(class), if you want to protect a static variable (or if the critical section occurs in a static method in the given class).
lock ensures that one thread does not enter a critical section while another thread is in the critical section of code.
Section 8.12 of the C# Language Reference discusses lock.
The following sample shows a simple use of threads in C#.
using System; using System.Threading; class ThreadTest { public void runme() { Console.WriteLine("Runme Called"); } public static void Main() { ThreadTest b = new ThreadTest(); Thread t = new Thread(new ThreadStart(b.runme)); t.Start(); } }
Runme Called
The following sample uses threads and lock. As long as the lock statement is present, the statement block is a critical section and balance
will never become a negative number.
using System; using System.Threading; internal class Account { int balance; Random r = new Random(); internal Account(int initial) { balance = initial; } internal int Withdraw(int amount) { if (balance < 0) { throw new Exception("Negative Balance"); } // Comment out the next line to see the effect of leaving out the lock keyword lock (this) { if (balance >= amount) { Thread.Sleep(5); balance = balance - amount; return amount; } else { return 0; // transaction rejected } } } internal void DoTransactions() { for (int i = 0; i < 100; i++) { Withdraw(r.Next(-50, 100)); } } } internal class Test { static internal Thread[] threads = new Thread[10]; public static void Main() { Account acc = new Account (0); for (int i = 0; i < 10; i++) { Thread t = new Thread(new ThreadStart(acc.DoTransactions)); threads[i] = t; } for (int i = 0; i < 10; i++) { threads[i].Start(); } } }