Wednesday, March 14, 2012

Lock Keyword in C#

Author : Prakash Pradeep Gopu


Let us consider two students have the common pen. if one is using the pen other has to block writing until the other user release the pen this we can see the below figure. This mechanism of blocking is called the “Lock “ in c#.
Lock is a keyword which blocks or restricts the code from being executed by more than one thread at same time. lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.

Syntax for declaring the Lock :

lock (Expression) <statementblock>

where Expression specifics the object  that you want to lock on.

Here is the example a static method “Call” that uses the lock stament on an object.This staments will block until the before thread is use to stop the method.


using System.Text;
using System.Threading;

namespace BloggerExamples
{
    class LockExample
    {
        static readonly object _object = new object();
        static void Call()
        {
            // Lock on the readonly object.
            // ... Inside the lock, sleep for 10000 milliseconds.
          
           lock (_object)
            {
                Console.WriteLine(DateTime.Now.ToString());
                Thread.Sleep(10000);
                Console.WriteLine(Environment.TickCount);
              
            }
        }

        static void Main()
        {
            // Create ten new threads.
            for (int i = 0; i < 10; i++)
            {
                //create a New thread and calling call method.
                ThreadStart start = new ThreadStart(Call);
                new Thread(start).Start();
               
            }
          
        }
    }
}

Output :
It blocks the every thread about  10 seconds until previous thread release the lock.







No comments:

Post a Comment