LockThe keyword marks the statement block as a critical section by obtaining the mutex lock of a given object, executing the statement, and releasing the lock. The statement format is as follows:
Object thisLock = new Object();
lock (thisLock)
{
// Critical code section
}
For more information, see thread synchronization (C # programming guide ).
Remarks
LockMake sure that when one thread is located in the Code critical section, the other thread does not enter the critical section. If other threads attempt to enter the locked code, it waits until the object is released.
Thread processing (C # programming guide) This section discusses thread processing.
LockCall Enter at the start of the block and Exit at the end of the block.
Generally, do not lockPublicType. Otherwise, the instance is out of the control range of the Code. Common StructureLock (this),Lock (typeof (MyType ))AndLock ("myLock ")Violation of this rule:
-
If the instance can be accessed by the publicLock (this)Problem.
-
IfMyTypePublic access is allowed.Lock (typeof (MyType ))Problem.
-
Because any other code using the same string in the process will share the same lockLock ("myLock ")Problem.
The best practice is to definePrivateObject To lock, orPrivate staticObject variables to protect the data shared by all instances.
Example
The following example shows a simple example of using a thread in C.
// statements_lock.cs
using System;
using System.Threading;
class ThreadTest
{
public void RunMe()
{
Console.WriteLine("RunMe called");
}
static void Main()
{
ThreadTest b = new ThreadTest();
Thread t = new Thread(b.RunMe);
t.Start();
}
}
Output
RunMe called
The following example uses the thread andLock. As longLockThe statement exists. The statement block is the critical section andBalanceIt will never be a negative number.
// statements_lock2.cs
using System;
using System.Threading;
class Account
{
private Object thisLock = new Object();
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(thisLock)
{
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));
}
}
}
class Test
{
static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account(1000);
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();
}
}
}