C# 应用 - 多线程 5) 死锁

两个线程中的每一个线程都尝试锁定另外一个线程已锁定的资源时,就会发生死锁。

两个线程都不能继续执行。

托管线程处理类的许多方法都提供了超时设定,有助于检测死锁。

例如,下面的代码尝试在 lockObject 对象上获取锁。 如果在 300 毫秒内没有获取锁,Monitor.TryEnter 返回 false。

if (Monitor.TryEnter(lockObject, 300)) 
{  
    try 
    { 
        // Place code protected by the Monitor here.  
    }  
    finally 
    {  
        Monitor.Exit(lockObject);  
    }  
}  
else
{  
    // Code to execute if the attempt times out.  
}  
posted @ 2021-03-11 12:28  鑫茂  阅读(128)  评论(0编辑  收藏  举报