c# 多线程解决死锁问题

可使用:Monitor.TryEnter()方法。虽然这种方法可以解决死锁问题,但是最好还是不要出现死锁这种情况。如果出现死锁这种情况,就说明代码有问题啊。还是在else里面加个日志记录下吧,然后再解决。以下代码来自互联网

    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) ;
            }
        }
    }

 

posted @ 2019-11-09 15:52  屌丝大叔的笔记  阅读(2766)  评论(0编辑  收藏  举报