In c#, the lock keyword is useful to acquire the mutual-exclusion of lock for the specified block of code to make sure that at a time, only one thread can execute it.
If any other thread wants to execute the same piece of code, then it should wait until the thread that holds the lock finishes its execution.
Generally, the lock
keyword is useful while working with multithreading applications to make sure that at a time, the only thread can access the particular piece of code.
Following is the syntax of using lock
keyword in c# to acquire the mutual-exclusion of lock for the specified piece of code.
Here, x is an expression of reference type, and within the lock
statement, we need to write the code which we want to allow access for one thread at a time.
Following is the example of using lock
keyword in c# to lock the particular piece of code to allow execution of one thread at a time.
If you observe the above example, we created multiple threads (t1 & t2) and starting to execute the PrintInfo method simultaneously. Here, in the PrintInfo method, we used lock
statement to acquire the mutual-exclusion of lock for the for loop code execution to allow only one thread execution at a time.
When we execute the above result, we will get the result as shown below.
If you observe the result, even if we start the multiple threads simultaneously to execute the same functionality, the lock
statement made the second thread wait until the first thread finishes its execution.
In the above example, if we didn’t use the lock
statement, then the multiple threads will execute simultaneously.
Following is the example of multithreading in c# without using lock
statement.
If you observe the above example, we created multiple threads (t1 & t2) and trying to execute the PrintInfo method. Here, in the PrintInfo method, we didn’t use any lock
statement so the threads will execute the PrintInfo method simultaneously.
When we execute the above program, we will get the result as shown below.
If you observe the result, multiple threads started executing the PrintInfo method simultaneously.
This is how we can use lock
statement in c# to acquire mutual-exclusion of lock for the specified block of code to make sure that at a time, only one thread can execute it based on our requirements.