Search code examples
c#multithreadingfile-ioreaderwriterlock

When using ReaderWriterLock does second thread actually wait or not


I am trying to write to a file using two threads. If I use ReaderWriterLock and while one thread is writing to file and second thread comes, will it actually wait for lock to release or it will just skip writing to file?


Solution

  • That depends on your action.

    Multiple threads can read the file while it's locked.*

    However, if you're trying to write to that file with a different thread while the lock is still being hold by another thread, the (new) thread will wait until it acquired the lock.

    Keep in mind that a timeout can be defined. As stated in the documentation

    If the time-out interval expires and the lock request has not been granted, the method returns control to the calling thread by throwing an ApplicationException. A thread can catch this exception and determine what action to take next.

    So, referring to your specific question: The file will indeed be skipped if a timeout has been set and that timeout has been exceeded.

    That timeout can be set using the AcquireWriterLock(TimeSpan timeout) overload.


    What's important to remember is that - if the thread calling AcquireWriterLock still has a valid reader lock - the operation will deadlock.

    If a thread calls AcquireWriterLock while it still has a reader lock, it will block on its own reader lock; if an infinite time-out is specified, the thread will deadlock. To avoid such deadlocks, use IsReaderLockHeld to determine whether the current thread already has a reader lock.


    * Note that a timeout can also be defined for reading using the AcquireReaderLock(int msTimeout) method. An ApplicationException will be thrown if the timeout expires before the lock has been granted, meaning reading will be skipped, too.