Introduction:

Here we will explain what is Lock Statement in C# or What is the benefit of using lock statement in C# or How to use it in C sharp programming with example.

 

Description:

The Lock statement is used in threading. It’s allow only one thread may acquire a particular monitor at one time. If a second thread attempts to acquire a particular monitor while a first thread is holding it, and it will wait, block, until the object is released. Once the execution is completed it releases the lock and frees objects.

 

Example:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
 
namespace Lock_Statement
{
    class Program
    {
        static readonly object obj = new object();
 
        static void A()
        {
            // Lock on the readonly object.
            // ...Inside the lock, sleep for 120 milliseconds.
            // ...This is thread serialization.
            lock (obj)
            {
                Thread.Sleep(120);
                Console.WriteLine(Environment.TickCount);
            }
        }
 
        static void Main()
        {
            //Create five new threads.
            for (int i = 0; i < 5; i++)
            {
                ThreadStart start = new ThreadStart(A);
                new Thread(start).Start();
            }
            Console.ReadLine();
        }
    }
}

 

 

Output:


How to use Lock statement in c#


I hope this article will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like