Use ReaderWriterLockSlim to Protect Access to Resources in C#
It is normally safe to allow let multiple threads read data at the same time, but when a thread is required to perform a write, all other threads will need to be blocked. The .NET framework originally provided ReaderWriterLock for this circumstance, but it has performance issues which often outweigh its usefulness. No address this, ReaderWriterLockSlim has been introduced which corrects many of the issues with ReaderWriterLock .
The below code demonstrates using a ReaderWriterLockSlim on an array which is shared between a single writer and three readers:
class ReaderWriterLockDemo
{
const int MaxNumberValues = 30;
static int[] _array = new int[MaxNumberValues];
static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(WriteThread);
for (int i = 0; i < 3; i++)
{
ThreadPool.QueueUserWorkItem(ReadThread);
}
Console.ReadKey();
}
static void WriteThread(object state)
{
int id = Thread.CurrentThread.ManagedThreadId;
for (int i = 0; i < MaxNumberValues; ++i)
{
_lock.EnterWriteLock();
Console.WriteLine(“Entered WriteLock on thread {0}”, id);
_array[i] = i*i;
Console.WriteLine(“Added {0} to array on thread {1}”, _
array[i], id);
Console.WriteLine(“Exiting WriteLock on the thread {0}”, id);
_lock.ExitWriteLock();
Thread.Sleep(1000);
}
}
static void ReadThread(object state)
{
int idNumber = Thread.CurrentThread.ManagedThreadId;
for (int i = 0; i < MaxNumberValues; ++i)
{
_lock.EnterReadLock();
Console.WriteLine(“Entered ReadLock on the thread {0}”, idNumber);
StringBuilder sbObj = new StringBuilder();
for (int j = 0; j < i; j++)
{
if (sbObj.Length > 0) sbObj.Append(“, “);
sbObj.Append(_array[j]);
}
Console.WriteLine(“Array: {0} on the thread {1}”, sbObj, idNumber);
Console.WriteLine(“Exiting the ReadLock on thread {0}”, idNumber);
_lock.ExitReadLock();
Thread.Sleep(10000);
}
}
}












No comments yet... Be the first to leave a reply!