Thứ Hai, 25 tháng 1, 2010

// // Leave a Comment

Lock keyword C#



The lock keyword allows a section of code to exclusively use a resource, a feature useful in multi-threaded applications. If a lock to the specified object is already held when a piece of code tries to lock the object, the code's thread is blocked until the object is available.

// Từ khoá "lock" cho phép một đoạn mã độc quyền sử dụng một nguồn tài nguyên, một đặc tính trong ứng dụng đa luồng. Nếu một khoá (lock) quy định đối tượng đã chiếm giữ khi mà đoạn mã đang khoá đối tượng, thread của đoạn mã bị chặn cho đến khi các đối tượng có giá trị.


using System;
using System.Threading;


class LockDemo
{
private static int number = 0;

private static object lockObject = new object();


private static void DoSomething()
{
while (true)

{
lock (lockObject)
{
int originalNumber = number;


number += 1;
Thread.Sleep((new Random()).Next(1000)); // sleep for a random amount of time

number += 1;
Thread.Sleep((new Random()).Next(1000)); // sleep again


Console.Write("Expecting number to be " + (originalNumber + 2).ToString());

Console.WriteLine(", and it is: " + number.ToString());
// without the lock statement, the above would produce unexpected results,

// since the other thread may have added 2 to the number while we were sleeping.
}
}
}

public static void Main()

{
Thread t = new Thread(new ThreadStart(DoSomething));


t.Start();
DoSomething(); // at this point, two instances of DoSomething are running at the same time.
}

}


The parameter to the lock statement must be an object reference, not a value type:

// Tham số của lock là một đối tượng tham chiếu, không phải là kiểu giá trị:


class LockDemo2
{
private int number;

private object obj = new object();

public void DoSomething()

{
lock (this) // ok
{
...
}


lock (number) // not ok, number is not a reference
{
...
}

lock (obj) // ok, obj is a reference

{
...
}
}
}









0 comments: