4

I have a class with two methods (one instance):

public class Example
{
    public void Connect()
    {
        // do stuff
    }

    public void DoSomething()
    {
        if (someCondition)
            Connect();

        // do stuff
    }
}

It is DoSomething allowed to be accessed by multiple threads at the same time. However, if Connect is called, no thread is allowed to enter DoSomething and vice versa, so Connect and DoSomething are mutually exclusive. DoSomething is called more often than Connect.

My first idea was to use ReaderWriterLockSlim, however, when DomeSomething aquires the reader lock and needs to call Connect itself, it cannot aquire the writer lock in Connect.

What synchronization pattern is most appropriate to achieve this goal?

Creepin
  • 482
  • 4
  • 20
  • The lock you want to use supports upgrading to write lock, so you may be able to use it. – Metheny Apr 25 '19 at 18:53
  • Entering the write lock throws a LockRecursionException: 'The current thread has entered read mode and doesn't already own a write lock, so trying to enter the lock in write mode would create the possibility of a deadlock.' If I use an `UpgradableReadLock` instead of a `ReadLock` multiple threads cannot enter – Creepin Apr 25 '19 at 18:58
  • Did you use EnterUpgradeableReadLock? https://learn.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim.enterupgradeablereadlock?view=netframework-4.7.2 – Metheny Apr 25 '19 at 19:03
  • 1
    The docs for `EnterUpgradeableReadLock` state: 'Only one thread can enter upgradeable mode at any given time.' So this is no replacement for the read lock. Using `EnterUpgradeableReadLock` would prevent multiple threads to access `DoSomething` at the same time. – Creepin Apr 25 '19 at 19:06
  • You can't ask for `Connect` and `DoSomething` to be mutually exclusive and then expect calling one from the other to work. What are you trying to achieve? – mostanes Jun 06 '19 at 14:13

0 Answers0