在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
可使用: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) ; } } }
|
请发表评论