- Demo.zip
- Archive created by free jZip.url
- Demo.Threading
- Demo.ParallelProcessing.Parallel
- Demo.ParallelProcessing.Tasks
- Demo.Threading.DeadLock
- Demo.Threading.Exception
- Demo.Threading.ForegroundThread
- Demo.Threading.Locks
- Demo.Threading.Performance
- Demo.Threading.ReadWriteLock
- Demo.Threading.sln
- Demo.Threading.suo
- Demo.Threading.Threadpool
- Demo.Threading.Web
- Demo.Threading.Windows
- Demo.Threading.WPF
- Demo.ThreadSync.AutoResetEvents
- Demo.ThreadSync.WaitHandles
- Demo_Threading.zip
- Demo.Threading
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Demo.Threading.ReadWriteLock
{
class Program
{
static List<int> myCollection = new List<int>();
static ReaderWriterLock rwLock = new ReaderWriterLock();
static void Main(string[] args)
{
// Thread 1 writing
new Thread(new ThreadStart(() =>
{
WriteToCollection(new int[]{1,2,3});
})).Start();
// Thread 2 Reading
new Thread(new ThreadStart(() =>
{
ReadFromCollection();
})).Start();
// Thread 3 Writing
new Thread(new ThreadStart(() =>
{
WriteToCollection(new int[] { 4, 5, 6 });
})).Start();
// Thread 4 Reading
new Thread(new ThreadStart(() =>
{
ReadFromCollection();
})).Start();
Console.ReadLine();
}
static void ReadFromCollection()
{
rwLock.AcquireReaderLock(5000);
try
{
Console.WriteLine("Read Lock acquired by thread : {0} @ {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("hh:mm:ss"));
Console.Write("Collection : ");
foreach (int item in myCollection)
{
Console.Write(item + ", ");
}
Console.Write("\n");
}
catch (Exception ex)
{
Console.WriteLine("Exception : " + ex.Message);
}
finally
{
Console.WriteLine("Read Lock released by thread : {0} @ {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("hh:mm:ss"));
rwLock.ReleaseReaderLock();
}
}
static void WriteToCollection(int[] num)
{
rwLock.AcquireWriterLock(5000);
try
{
Console.WriteLine("Write Lock acquired by thread : {0} @ {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("hh:mm:ss"));
myCollection.AddRange(num);
Console.WriteLine("Written to collection ............: {0}", DateTime.Now.ToString("hh:mm:ss"));
}
catch (Exception ex)
{
Console.WriteLine("Exception : " + ex.Message);
}
finally
{
Console.WriteLine("Write Lock released by thread : {0} @ {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("hh:mm:ss"));
rwLock.ReleaseWriterLock();
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
I am a Senior Software Developer / Technical Consultant in a leading software company.