C# 中的锁结构确保没有其他线程可以进入线程已经执行的代码部分。它使尝试进入代码段的其他线程等待或阻塞,直到执行线程完成其执行。在多线程编程中使用锁是一种更快、更方便的处理线程的方法。
语法
lock(object_name) statement_block
哪里,
查找下面的示例。
C# 程序演示当一个线程已经在代码的关键部分执行时,锁会阻止另一个线程的执行:
代码:
using System; using System.Threading; //a namespace called program is defined namespace program { //a class called check is defined class check { //an object that defines a lock is created static readonly object lockname = new object(); //a method called display is created in which the lock is used to make any other threads trying to access the method wait or block until thread that is already executing completes its execution static void display() { //keyword lock is used to lock the object lock (lockname) { for (int a = 1; a <= 3; a++) { //the output is displayed synchronously in a row by one thread followed by another thread because we have used lock on display method Console.WriteLine("The value to be printed is: {0}", a); } } } static void Main(string[] args) { //an instance of the thread is created and the corresponding thread is executed on the display method Thread firstthread = new Thread(display); //an instance of the thread is created and the corresponding thread is executed on the display method Thread secondthread = new Thread(display); firstthread.Start(); secondthread.Start(); Console.ReadLine(); } } }
输出:
说明:在上面的程序中,程序定义了一个名为“program”的命名空间。然后它定义了一个名为“check”的类。此方法利用锁来使尝试访问它的任何其他线程等待或阻塞,直到当前正在执行的线程完成其执行。上面的快照显示了输出。
C# 程序演示当一个线程已经在代码的关键部分执行时,锁会阻止另一个线程的执行:
代码:
using System; using System.Threading; //a namespace called program is defined namespace program { //a class called check is defined class check { //an object that defines a lock is created static readonly object lockname = new object(); //a method called display is created in which the lock is used to make any other threads trying to access the method wait or block until thread that is already executing completes its execution static void display() { //keyword lock is used to lock the object lock (lockname) { for (int a = 1; a <= 3; a++) { //the output is displayed synchronously in a row by one thread followed by another thread because we have used lock on display method Console.WriteLine("The first three lines are printed by first thread and the second three lines are printed by the second thread"); } } } static void Main(string[] args) { //an instance of the thread is created and the corresponding thread is executed on the display method Thread firstthread = new Thread(display); //an instance of the thread is created and the corresponding thread is executed on the display method Thread secondthread = new Thread(display); firstthread.Start(); secondthread.Start(); Console.ReadLine(); } } }
输出:
说明:程序定义了一个名为“program”的命名空间,然后定义了一个名为“check”的类。它创建一个代表锁的对象。它使用关键字“lock”来锁定先前创建的对象。
在本教程中,我们通过编程示例及其输出来了解锁的定义、语法和工作原理,从而了解 C# 锁定的概念。
以上是C# 中的锁定的详细内容。更多信息请关注PHP中文网其他相关文章!