When working with a multithreading application it is very important for developers to handle multiple threads for a critical section of code.

Monitor and lock is the way to provide thread safety in a multithreaded application in C#. Both provide a mechanism to ensure that only one thread is executing code at the same time to avoid any functional breaking of code.

Lock

Lock is the keyword in C# that will ensure one thread is executing a piece of code at one time. The lock keyword ensures that one thread does not enter a critical section of code while another thread is in that critical section.

Lock is a keyword shortcut for acquiring a lock for the piece of code for only one thread.

Example:

class Program  
{
static readonly object _object = new object();
    static void TestLock()  
    {  

        lock (_object)  
        {  
            Thread.Sleep(100);  
            Console.WriteLine(Environment.TickCount);  
        }  
    }  

    static void Main(string[] args)      
    {  
        for (int i = 0; i < 10; i++)  
        {  
            ThreadStart start = new ThreadStart(TestLock);  
            new Thread(start).Start();  
        }  

        Console.ReadLine();  
    }  
}  

Souces:

https://www.c-sharpcorner.com/UploadFile/de41d6/monitor-and-lock-in-C-Sharp/

Last modified: April 1, 2019

Author

Comments

Write a Reply or Comment