Stream synchronization with multiple methods

I have a static class with several static methods.

private static Session _session = new Session();

public static void Method1() {
    if(_session != null)
        _session.Action();
}
public static void Method2() {
    if(_session != null)
        _session.Action();
}
public static void Method3() {
    if(_session != null)
        _session.Action();
}
public static void Method4(string path) {
    _session.Disconnect();
    _session.Connect(new Config(path));
}

Method1, Method2, Method3 are completely thread safe, they can be safely called simultaneously from any number of threads. In fact, for performance reasons, I need to allow multiple threads to call method1,2 at the same time.

The problem is that Method1,2,3 can throw an exception when Method4 () is called. How to allow several threads to call Method1,2,3, and also block them when calling method4 ()?

+3
source share
3 answers

As SLaks noted, ReadWriterLock is a great solution.

Here is what I ended up with:

private static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
private static Session _session = new Session();

public static void Method1() {
    _lock.EnterReadLock();
    try {
        if(_session != null)
            _session.Action();
    }
    finally
    {
        _lock.ExitReadLock();
    }
}
public static void Method2() {
    _lock.EnterReadLock();
    try {
        if(_session != null)
            _session.Action();
    }
    finally
    {
        _lock.ExitReadLock();
    }
}
public static void Method3() {
    _lock.EnterReadLock();
    try {
        if(_session != null)
            _session.Action();
    }
    finally
    {
        _lock.ExitReadLock();
    }
}
public static void Method4(string path) {
    _lock.EnterWriteLock();
    try {
        if(_session != null)
            _session.Action();
    }
    finally
    {
        _lock.ExitWriteLock();
    }
}

Great performance, no threading issues!

+4
source
private static RefCountDisposable _refCountDisposible = new RefCountDisposable();
private static Session _session = new Session();

public Constructor()
{
    _refCountDisposible = new RefCountDisposable(
           Disposible.Create(() => _session.Disconnect()));
}

public static void Method1() {
    using(_refCountDisposible.GetDisposible())
        if(_session != null)
            _session.Action();

}
public static void Method2() {
    using(_refCountDisposible.GetDisposible())

        if(_session != null)
            _session.Action();
}
public static void Method3() {
    using(_refCountDisposible.GetDisposible())
        if(_session != null)
            _session.Action();
}
public static void Method4(string path) {
    _refCountDisposible.Dispose()
}
0
source

What about ManualResetEvent?

M4()
{
  _event.Reset();
  try
    //reconnect
  finally
    _event.Set();
}

M1,2,3()
{
  _event.WaitOne();
  //do actions
}
-2
source

All Articles