CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Tuesday, March 11, 2008

ReaderWriterLock in C#.NET using System.Threading

ReaderWriterLock is available in System.Threading. ReaderWriterLock is used to acquire locks for a given resource. It allows either concurrent read access for multiple threads, or write access for a single thread. A thread can hold a reader lock or a writer lock, but not both at the same time. Instead of releasing a reader lock in order to acquire the writer lock, you can use UpgradeToWriterLock and DowngradeFromWriterLock.

     ReaderWriterLock works best where most accesses are reads and writes  are of infrequent and short duration. Readers and writers are queued separately. When a thread releases the writer lock, all threads waiting in the reader queue at that instant are granted reader locks; when all of those reader locks have been released, the next thread waiting in the writer queue, if any, is granted the writer lock, and so on. Multiple readers alternate with single writers, so that neither readers nor writers are blocked for long periods.While a thread in the writer queue is waiting for active reader locks to be released, threads requesting new reader locks accumulate in the reader queue. Their requests are not granted, even though they could share concurrent access with existing reader-lock holders; this helps protect writers against indefinite blockage by readers.

     Most methods for acquiring locks on a ReaderWriterLock accept time-out values. Using time-outs avoid deadlocks in your application. 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.

private static ReaderWriterLock objLock 
= new ReaderWriterLock();
private const int iTimeoutMillisecs = 100;
private Dictionary<string, string> observerList;

//Acquiring WriterLock

try
{
objLock.AcquireWriterLock(iTimeoutMillisecs);

//do something………….
observerList.Add("Test", "Test One");
}
finally
{
objLock.ReleaseWriterLock();
}

//Acquiring ReaderLock

try
{
objLock.AcquireReaderLock(iTimeoutMillisecs);
//do something
}
finally
{
objLock.ReleaseReaderLock();
}

Post a Comment