6

释放锁时,我收到 SynchronizationLockException。

当然,我做的第一件事是谷歌搜索这个问题。我发现了两个主要的错误模式:

  1. 在与创建的线程不同的线程上释放 Mutex。
  2. 使用值类型作为 Monitor 的同步对象。或者修改进入和退出 Monitor 之间的同步对象。

问题是这些模式都不适合我的情况。

我有一个非常简单的同步场景:

public class MyClass : IDisposable
{
    private readonly object _myLock = new object();

    internal void Func1()
    {
        lock (_myLock)
        {
            //Some code here
        }
    }

    internal void Func2()
    {
        lock (_myLock)
        {
            //Some code here
        }
    }

    public void Dispose()
    {
        lock (_myLock)
        {
            //Some code here
        }  // Here is where I get an exception
    }
}

最终我收到了释放锁SynchronizationLockException的行。Dispose()

My question is not "What is the problem with my code" or "What am I doing wrong". Basically, I would like to know how (and under which circumstances) this could possibly happen that .NET implementation of lock throws this exception.

Thanks.

4

1 回答 1

0

I once got the SynchronizationLockException in List instance when it has been resizing its underlying array to fit new elements. The List instance has been accessed from three different threads and there was one lock missing...

I'd say: Triple check if you're doing thread synchronization the right way.

Furthermore, implement the IDisposable pattern the right way (see http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx). Maybe finalizer is giving you a headache.

于 2012-12-28T21:41:22.990 回答