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中文網其他相關文章!