C# 编程/关键字/lock
外观
< C Sharp 编程 | 关键字
在多线程应用程序中,lock
关键字允许一段代码独占使用资源。如果当一段代码尝试锁定某个对象时,该对象的锁已被其他代码占用,则这段代码所在的线程将被阻塞,直到该对象可用。
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.
}
}
lock 语句的参数必须是对象引用,而不是值类型。
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
{
...
}
}
}
C# 关键字 | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
特殊的 C# 标识符(上下文关键字) | |||||||||||||||
| |||||||||||||||
上下文关键字(用于查询) | |||||||||||||||
|