Skip to main content
 首页 » 编程设计

c#之没有为其他线程释放锁

2024年02月01日37leader

我有 5 个线程试图在随机时间进入静态类的关键部分。如果另一个线程在关键部分,我希望其他线程“退后”并稍后再试。问题是,似乎在第一个线程进入临界区后锁没有被释放,因为对于其他线程,如果我在 Monitor.TryEnter(thisLock) 处设置“断点”,将始终返回 false。 任何帮助,将不胜感激。谢谢。

这是我的代码:

static class Receiver 
    { 
        public static object thisLock = new object(); 
        public static int success; 
 
        public static bool hasLocked() 
        { 
            if(Monitor.TryEnter(thisLock)) 
            { 
                Monitor.Enter(thisLock); 
                System.Threading.Thread.Sleep(10); 
                success++; 
                Monitor.Exit(thisLock); 
                return true; 
            } 
            return false; 
        } 
    } 

请您参考如下方法:

It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.

http://msdn.microsoft.com/en-us/library/de0542zz%28v=vs.110%29.aspx

基本上,您在代码中获得了两次锁。您需要删除对 Monitor.Enter 的调用,因为 Monitor.TryEnter 已经获得了锁。

static class Receiver 
{ 
    public static object thisLock = new object(); 
    public static int success; 
 
    public static bool hasLocked() 
    { 
        if(Monitor.TryEnter(thisLock)) 
        { 
            System.Threading.Thread.Sleep(10); 
            success++; 
            Monitor.Exit(thisLock); 
 
            return true; 
        } 
 
        return false; 
    } 
}