Lock keyword in C#

As we have written earlier we have now multi-core CPU for our computers and laptops and to utilize that we need to use threading in code. Now if we create thread and access same resource at same time then it will create a problem at that time locking become quite essential in any programming language.

Let’s consider a scenario. We are having a small firm of computers and each computer is shared by two employees and they need to use computer for putting their sales data in excel sheet. So they can not work together at same time and one has to work and other has to wait till first one complete the work. Same situation can be occurred in programming in where we are using same resource for multiple thread.

C# provides locking mechanism via lock keyword. It restricts code from being executed by more then one thread at a time. That is the most reliable way of doing multi threading programming.


Now Let’s take simple example for that. Following is a code for that.

using System;
using System.Threading;

namespace ThreadLock
{
    class Program
    {
        static readonly object lockObject=new object();
        static int value1 = 2;
        static int value2 = 3;


        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                ThreadStart start = new ThreadStart(Add);
                new Thread(start).Start();
                Console.WriteLine("Thread {0} started", i + 1);
            }
        }

        static void Add()
        {
            lock (lockObject) {
                Thread.Sleep(100);
                value1 = value1 + value2;
                Console.WriteLine(value1);
            }
        }
    }
}

Here you can I have created object called lockobject and in Add method I have lock that object with Lock keyword and then I am printing value of addition via Console.WriteLine.  Now if you see the I have created 10 threads for same add method but it will wait for previous thread to complete work as now its thread safe.

Now if you run this example you will see it will wait for the previous thread to complete addition. Following is a output as expected.

Lock example in C# to make threadsafe


Hope you like it. Stay tuned for more..

Shout it

kick it on DotNetKicks.com

No comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.