Jump to content
Wikibooks The Free Textbook Project

C# Programming/Keywords/lock

From Wikibooks, open books for an open world
The latest reviewed version was checked on 16 April 2020. There are template/file changes awaiting review.

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.

usingSystem;
usingSystem.Threading;
classLockDemo
{
privatestaticintnumber=0;
privatestaticobjectlockObject=newobject();

privatestaticvoidDoSomething()
{
while(true)
{
lock(lockObject)
{
intoriginalNumber=number;

number+=1;
Thread.Sleep((newRandom()).Next(1000));// sleep for a random amount of time
number+=1;
Thread.Sleep((newRandom()).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.
}
}
}

publicstaticvoidMain()
{
Threadt=newThread(newThreadStart(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:

classLockDemo2
{
privateintnumber;
privateobjectobj=newobject();

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

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

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



C# Keywords
Special C# Identifiers (Contextual Keywords)
Contextual Keywords (Used in Queries)

AltStyle によって変換されたページ (->オリジナル) /