I have basic knowledge of C#. Please explain the purpose of the 'lock' keyword in C# and its uses.
Loading
I have basic knowledge of C#. Please explain the purpose of the 'lock' keyword in C# and its uses.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Mithilesh TataPosted Mar 5, 2024, 8:40 AM
The purpose of the 'lock' keyword in C# is to provide a simple and effective way to synchronize access to shared resources in a multi-threaded environment. It helps prevent race conditions where multiple threads may attempt to access or modify the same resource concurrently, leading to unpredictable behavior or data corruption.
Here's how the 'lock' keyword works:
Here's a basic example demonstrating the usage of the 'lock' keyword:
class SharedResource
{
private int counter = 0;
private object lockObject = new object();
public void IncrementCounter()
{
lock (lockObject) // Acquire a lock on the lockObject
{
counter++; // Critical section - accessing shared resource
} // Release the lock
}
}
In this example, multiple threads may call the 'IncrementCounter' method concurrently. However, only one thread at a time can execute the critical section of code within the 'lock' statement, ensuring that the 'counter' variable is incremented safely without risk of data corruption due to concurrent access.
It's important to note that the object specified in the 'lock' statement serves as the synchronization object, and it's crucial to choose a suitable object to lock on to prevent deadlocks or contention issues. Additionally, the 'lock' statement automatically releases the lock even if an exception occurs within the critical section, ensuring proper synchronization.
Tuhin PaulPosted Mar 10, 2024, 2:53 AM
In this example:
BankAccountclass representing a bank account with methods to deposit and withdraw funds, as well as a method to retrieve the balance.lockkeyword to synchronize access to thebalancefield within the deposit and withdrawal methods to ensure thread safety.Tuhin PaulPosted Mar 10, 2024, 2:53 AM
let's consider a scenario where multiple threads are accessing and modifying a shared resource, such as a bank account balance. Without proper synchronization, concurrent access to the balance could lead to incorrect results due to race conditions. We'll use the
lockkeyword to ensure that only one thread can access the balance at a time, preventing data corruption.Rajanikant HawaldarPosted Mar 5, 2024, 5:35 PM
https://www.c-sharpcorner.com/UploadFile/de41d6/monitor-and-lock-in-C-Sharp/