C# 中的 lock 语句
Muhammad Maisam Abbas
2021年3月21日
在本教程中,我们将讨论 C# 中的 lock
语句。
C# 中的 lock
语句
lock(obj)
语句规定,在 C# 中,下面这段代码不能被多个线程同时访问。lock(obj)
语句中的 obj
参数是 object
类的实例。lock(obj)
语句提供了一种在 C# 中管理线程的有效方法。如果一个线程访问 lock(obj)
内的代码,而另一个线程想要访问相同的代码,则第二个线程将不得不等待第一个线程执行它。lock(obj)
语句可确保顺序执行指定的代码段。为了演示这种现象,我们将首先使用 lock(obj)
语句向你显示代码的结果,而不用任何线程管理。
using System;
using System.Threading;
namespace lock_statement
{
class Program
{
static readonly object lockname = new object();
static void display()
{
for (int a = 1; a <= 3; a++)
{
Console.WriteLine("The value to be printed is: {0}", a);
}
}
static void Main(string[] args)
{
Thread firstthread = new Thread(display);
Thread secondthread = new Thread(display);
firstthread.Start();
secondthread.Start();
}
}
}
输出:
The value to be printed is: 1
The value to be printed is: 1
The value to be printed is: 2
The value to be printed is: 3
The value to be printed is: 2
The value to be printed is: 3
我们可以看到,线程 firstthread
和 secondthread
都随机访问循环内的代码。我们将通过 lock(obj)
语句向你显示线程管理的代码结果。
using System;
using System.Threading;
namespace lock_statement
{
class Program
{
static readonly object lockname = new object();
static void display()
{
lock (lockname)
{
for (int a = 1; a <= 3; a++)
{
Console.WriteLine("The value to be printed is: {0}", a);
}
}
}
static void Main(string[] args)
{
Thread firstthread = new Thread(display);
Thread secondthread = new Thread(display);
firstthread.Start();
secondthread.Start();
}
}
}
输出:
The value to be printed is: 1
The value to be printed is: 2
The value to be printed is: 3
The value to be printed is: 1
The value to be printed is: 2
The value to be printed is: 3
这次,firstthread
和 secondthread
依次访问循环内的代码。我们可以将用来更改变量值的代码放在 lock(obj)
语句中,以防止任何数据丢失。
Author: Muhammad Maisam Abbas
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn