Lock Statement (C # Statement)

Source: Internet
Author: User

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();
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.