c # multithreading resolve deadlocks

Can be used: Monitor.TryEnter () method, the code from the Internet.

While this approach can solve the deadlock problem, but it is best not to deadlock the case. If a deadlock this happens, it shows the code in question ah. Or else in which to add a log to record it, and then resolve.

    class Program
    {
        static void Main(string[] args)
        {
            object lock1 = new object();
            object lock2 = new object();

            new Thread(() => LockTooMuch(lock1, lock2)).Start();

            lock (lock2)
            {
                Thread.Sleep(1000);
                Console.WriteLine("Monitor.TryEnter allows not to get stuck,returning false after a specified timeout is elapsed");
                if (Monitor.TryEnter(lock1, TimeSpan.FromSeconds(5)))
                {
                    Console.WriteLine("Acquired a protected resource succesfully");
                }
                else
                {
                    Console.WriteLine("Timeout acquiring a resource!");
                }
            }
            //new Thread(() => LockTooMuch(lock1, lock2)).Start();

            //Console.WriteLine("----------------------------------");
            //lock (lock2)
            //{
            //    Console.WriteLine("This will be a deadlock!");
            //    Thread.Sleep(1000);
            //    lock (lock1)
            //    {
            //        Console.WriteLine("Acquired a protected resource succesfully");
            //    }
            //}

            Console.ReadKey();
        }

        static void LockTooMuch(object lock1, object lock2)
        {
            lock (lock1)
            {
                Thread.Sleep(1000);
                lock (lock2) ;
            }
        }
    }

 

Guess you like

Origin www.cnblogs.com/subendong/p/11826347.html