Lock. This C# keyword is used in threading. It restricts code from being executed by more than one thread at the same time. This makes threaded programs reliable.
The lock statement uses a special syntax form to restrict concurrent access. Lock is compiled into a lower-level implementation based on threading primitives.
An example. The Main method creates 10 new threads, and then calls Start on each one. Please examine method "A" to see the lock statement.
Detail This uses lock on an object. Each invocation of this method accesses the threading primitives implemented by the lock.
Then Only one method A can call the statements protected by the lock at a single time, regardless of the thread count.
Info Method A is invoked 10 times. The output shows the protected method region is executed sequentially—about 100 milliseconds apart.
using System;
using System.Threading;
class Program
{
static readonly object _object = new object();
static void A()
{
// Method A: lock on the readonly object.// ... Inside the lock, sleep for 100 milliseconds.// ... This is thread serialization.
lock (_object)
{
Thread.Sleep(100);
Console.WriteLine(Environment.TickCount);
}
}
static void Main()
{
// Create 10 new threads.
for (int i = 0; i < 10; i++)
{
ThreadStart start = new ThreadStart(A);
new Thread(start).Start();
}
}
}28106840
28106949
28107043
28107136
28107246
28107339
28107448
28107542
28107636
28107745
IL. Let's examine the intermediate representation for the lock statement. In compiler theory, high-level source texts are translated to lower-level streams of instructions.
A summary. Lock is a synchronization construct. We looked at an example and stepped into the IL. This keyword is helpful for threaded programs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 11, 2021 (edit).