Search code examples
c#multithreadingthread-safetylockingreaderwriterlockslim

Multiple ReaderWriterLockSlim on a Resource


ReaderWriterLockSlim allows a lock that is used to manage access to a resource, allowing multiple threads for reading or exclusive access for writing. currently we have the following code in place:

public ReaderWriterLockSlim protDataA = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
        public ReaderWriterLockSlim protDataB = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
        public void AMethod(ClassA Aobject )
        {
            try
            {
                protDataA.EnterWriteLock();
                //change A-typed-object
            }
            finally
            { protDataA.ExitWriteLock(); }
        }
        public void BMethod(ClassB Bobject)
        {
            try
            {
                protDataB.EnterWriteLock();
                //change B-typed-object
            }
            finally
            { protDataB.ExitWriteLock(); }
        }

Now, If I need to protect data for both A and B typed objects what should be the approach and Why ?

//Approach-1 - Making multiple locks on a single block
public void ABMethod(ClassA Aobject, ClassB Bobject)
            {
                try
                {
                    protDataA.EnterWriteLock();
                    protDataB.EnterWriteLock();
                    //change A-typed-object
                    //change B-typed-object
                }
                finally
                {
                    protDataA.ExitWriteLock();
                    protDataB.ExitWriteLock();
                }
            }

    //Approach-2 - Or Making a single lock would serve the same purpose ?
            public void ABMethod(ClassA Aobject, ClassB Bobject)
            {
                try
                {
                    protDataA.EnterWriteLock();
                    //change A-typed-object
                    //change B-typed-object
                }
                finally
                {
                    protDataA.ExitWriteLock();
                }
            }

Solution

  • Both approaches are good. Choosing the best one requires knowledge about other usages of the locks: how often they are locked, how long, etc.

    Until there is a certain perfomance bottleneck (found via profiling), the second(single lock) approach is preferred: it never suffers from deadlock, so you have lower chance to make bugged code.