C# Keywords Tutorial Part 52: lock

C# Keywords Tutorial Part 52: lock

C# is a flexible and strong programming language that gives programmers a wide range of tools to create strong applications. A feature that helps to guarantee that only one thread at a time may access a crucial part of code is the “lock” keyword. We will examine the “lock” keyword and its applications in C# in this blog article.

Race problems are avoided in multi-threaded programs by using the “lock” keyword. It functions by enclosing a crucial part of code with a lock so that only one thread may access it at once. This avoids conflicts and data damage caused by many threads accessing the same shared resource concurrently.

Here is an example of how the “lock” keyword can be used in C#:

class Program
{
? ? static void Main(string[] args)
? ? {
? ? ? ? // Create a new instance of the Counter class
? ? ? ? Counter counter = new Counter();


? ? ? ? // Create two threads that will increment the counter
? ? ? ? Thread thread1 = new Thread(() => counter.Increment());
? ? ? ? Thread thread2 = new Thread(() => counter.Increment());


? ? ? ? // Start both threads
? ? ? ? thread1.Start();
? ? ? ? thread2.Start();


? ? ? ? // Wait for both threads to finish
? ? ? ? thread1.Join();
? ? ? ? thread2.Join();


? ? ? ? // Print the final value of the counter
? ? ? ? Console.WriteLine("Counter value: {0}", counter.Value);
? ? }
}


class Counter
{
? ? private int value;


? ? // Increment the counter
? ? public void Increment()
? ? {
? ? ? ? for (int i = 0; i < 100000; i++)
? ? ? ? {
? ? ? ? ? ? lock (this)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? value++;
? ? ? ? ? ? }
? ? ? ? }
? ? }


? ? // Get the current value of the counter
? ? public int Value
? ? {
? ? ? ? get { return value; }
? ? }
}        

In this example, we have a Counter class that has a private “value” field and two methods: “Increment” and “Value”. The “Increment” method uses a “for” loop to increment the value of the counter 100,000 times. The “lock” keyword is used to create a lock around the critical section of code that increments the value of the counter. This ensures that only one thread at a time can access this section of code.

We create two threads that call the “Increment” method of the Counter class, and we start both threads. We then wait for both threads to finish before printing the final value of the counter.

Using the “lock” keyword can help to prevent race conditions in multi-threaded applications and ensure that only one thread at a time can access a critical section of code. However, it is important to use the “lock” keyword judiciously, as it can cause performance issues if used excessively.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了