Monday 19 October 2015

How to avoid deadlock in c#?

To avoid deadlock you can use  Monitor.TryEnter  instead of lock.
In the below example, DoWork1 will acquire lock on staticObjLock2 for 10 Seconds. If lock cannot be acquired it prints a message and return.
 

Example:- 

 
class Program
    {
        private static object staticObjLock1 = new object();
        private static object staticObjLock2 = new object();
 
 
        static void Main()
        {
                     Thread thread1 = new Thread(DoWork1);
            Thread thread2 = new Thread(DoWork2);
 
            thread1.Start();
            thread2.Start();
 
            thread1.Join();
            thread2.Join();
 
            Console.WriteLine("Processing done!");
            Console.ReadLine();
 
 
         }
 
        private static void DoWork1()
        {
            lock (staticObjLock1)
            {
                Console.WriteLine("try to accquire lock on objectB");
                Thread.Sleep(1000);
                if (Monitor.TryEnter(staticObjLock2, 10000))
                {
                    try
                    {
                        // this will never execute
                        Console.WriteLine("in DoWork2 critical section");
                    }
                    finally
                    {
                        Monitor.Exit(staticObjLock2);
                    }
                }
                else
                {
                    Console.WriteLine("Unable to acquire lock.");
                }
            }
        }
        private static void DoWork2()
        {
            lock (staticObjLock2)
            {
                Console.WriteLine("try to accquire lock on objectA");
                //Thread.Sleep(1000);
                lock (staticObjLock1)
                {
                    // this will never execute
                    Console.WriteLine("in DoWork2 critical section");
                }
            }
        }
 
    }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.