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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Mithilesh TataRank #862 · 2.6K reputationPosted Mar 5, 2024, 3:40 AM EST
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.
Rajanikant HawaldarRank #110 · 20.4K reputationPosted Mar 5, 2024, 12:35 PM EST
https://www.c-sharpcorner.com/UploadFile/de41d6/monitor-and-lock-in-C-Sharp/
Tuhin PaulRank #7 · 71.9K reputationPosted Mar 9, 2024, 9:53 PM EST
using System; using System.Threading; class BankAccount { private decimal balance; private object balanceLock = new object(); // Object used for synchronization public BankAccount(decimal initialBalance) { balance = initialBalance; } public decimal GetBalance() { lock (balanceLock) { return balance; } } public void Deposit(decimal amount) { lock (balanceLock) { balance += amount; Console.WriteLine($"Deposited {amount}. New balance: {balance}"); } } public void Withdraw(decimal amount) { lock (balanceLock) { if (balance >= amount) { balance -= amount; Console.WriteLine($"Withdrawn {amount}. New balance: {balance}"); } else { Console.WriteLine("Insufficient funds for withdrawal."); } } } } class Program { static void Main(string[] args) { BankAccount account = new BankAccount(1000); // Create multiple threads to simulate concurrent access Thread[] threads = new Thread[5]; for (int i = 0; i { // Simulate deposit and withdrawal operations Random random = new Random(); for (int j = 0; j < 3; j++) { decimal depositAmount = random.Next(100, 500); decimal withdrawalAmount = random.Next(100, 500); account.Deposit(depositAmount); account.Withdraw(withdrawalAmount); } }); threads[i].Start(); } // Wait for all threads to complete foreach (Thread thread in threads) { thread.Join(); } // Display final balance Console.WriteLine($"Final balance: {account.GetBalance()}"); } }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.Tuhin PaulRank #7 · 71.9K reputationPosted Mar 9, 2024, 9:53 PM EST
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.