0

I need to allow multiple writers/single-reader at the same time.

I have found ReaderWriterLockSlim class but I have a problem with the naming. I need to use EnterReadLock() for allowing writer to write and EnterWriteLock() for allowing reader to write, which can be a bit confusing for further use.

Does ReaderWriterLockSlim class have a wrapper class for my issue or can you suggest another solution.

Thanks!

L_D
  • 11
  • 4

2 Answers2

0

If you can use .Net 4.5 or later, I recommend using the Task Parallel Library's BufferBlock class. (You install the TPL via Nuget.)

See here and here for sample code.

Alternatively, you could look in to using BlockingCollection, which is supported by .Net 4.0 or later.

Both these classes make it relatively easy to share a queue between multiple writers and a single reader.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • 1
    It is important to note that even though each method of BlockingCollection is thread-safe, an operation with multiple calls to BlockingCollection will not be atomic, and thus the user still need to use an additional locking model or a different coding model to simulate an atomic operation when accessing multiple methods of the object. BTW, collections like BlockingCollection and ConcurrentDictionary has methods that work with check-then-perform model as in do something only if a condition is satisfied (atomic) to try to eliminate the issue I have just described. – m1o2 Mar 02 '16 at 07:32
0

Is this what you are looking for? Altough i would suggest you to stick to regular naming convention, making it easier for futur update from another guy.

class MyReaderWriterLockSlim: ReaderWriterLockSlim
{
    new public void EnterWriteLock()
    { base.EnterReadLock(); }

    new public void EnterReadLock()
    { base.EnterWriteLock(); }

    new public void ExitReadLock()
    { base.ExitWriteLock(); }

    new public void ExitWriteLock()
    { base.ExitReadLock(); }
}

class Program
{
    private static void Main(string[] args)
    {
        MyReaderWriterLockSlim myLock=new MyReaderWriterLockSlim();
        myLock.EnterReadLock();
        try
        {
            //do stuff
        }
        finally 
        { myLock.ExitReadLock(); }
    }
}
Fraco
  • 1