C# Handle two methods with same lock differently

126 Views Asked by At

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?

0

There are 0 best solutions below