The LOCK keyword can mark the statement block as a critical area, and the method is to obtain a mutex, execute the statement, and then release the lock. The form of this statement is as follows: Lock (Expression) Statement_block where: Expression specifies the object to be locked. Expression must be a reference type. Typically, if you want to protect instance variables, Expression is this; if you want to protect Static variables (or if the critical area appears in a given static method), Expression is TypeOf (Class). The statement of the Statement_block critical area. Remarks Lock Make sure that another thread does not enter the critical area when a thread is located in the critical area of the code. If other threads are trying to enter a locked code, it will wait (block) before release the object. 8.12 LOCK statement discusses the LOCK. Example 1 The following example shows a simple example of using a thread in C #. // statements_lock.csisting system; using system.threading;
Class threadtest {public void runme () {console.writeLine ("runme caled";}
Public static void main () {threadTest B = New Threadtest (); thread T = New Thread (New ThreadStart (B.RunME)); T.Start ();}} Output RunME Called Example 2 The following example uses threads and LOCK. As long as the LOCK statement exists, the statement is a critical area and Balance will never be negative. // statements_lock2.csusing system; using system.threading;
Class Account {Int Balance;
Random r = new random ();
Public Account (int initial) {balance = initial;
INT withDRAW (int Amount) {
// this condition will never be true unless the lock statement // is commented out: 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) {Console.Writeline ("Balance Before withdrawal: balance); console.writeline ("Amount to Withdraw: -" Amount); Balance = Balance - Amount; Console.Writeline ("Balance After Withdrawal: Balance); Return Amount;} else {return 0; // Transaction rejected}}} public void Dotransactions () {for (int i = 0; i <100; i ) {withdraw (R.Next (1, 100));}}}