C# Lock Statement

In this article i am explaining about lock statement in c#. The lock statement handle lock segment as a critical section and lock the object during the execution of program from other thread. 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;
namespace Lock_Statement
{
    class Program
    {
        public void PrintName()
        {
            Console.WriteLine("My name is Pawan Shukla");
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            // creating lock segment. all the resources that is used in lock segment, can't be used by another thread until it releases.
            lock (obj)
            {
                obj.PrintName();
            }
            Console.ReadLine();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *