ReaderWriterLockSlim.EnterUpgradeableReadLock() Always A Deadlock?

前端 未结 3 1501
慢半拍i
慢半拍i 2020-12-30 13:13

I\'m very familiar with ReaderWriterLockSlim but tried my hand at implementing EnterUpgradeableReadLock() recently in a class... Soon after I reali

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 13:51

    You have an error in your example

    private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
    

    it should be

    private static readonly ReaderWriterLockSlim _lock = new  ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
    

    Now in your code everytime a class is instantianed it is creating new instance of ReaderWriterLockSlim which is unable to lock anything because every single thread has it's own instance of it. Making it static will force all threads to use one instance which will work as it should

提交回复
热议问题