classProgram
{
StaticvoidMain ()
{
NewThread (Read) {IsBackground =true}. Start ();
NewThread (Read) {IsBackground =true}. Start ();
NewThread (Read) {IsBackground =true}. Start ();
NewThread (Read) {IsBackground =true}. Start ();
NewThread (Read) {IsBackground =true}. Start ();
NewThread (() = Write ("T1") {IsBackground =true}. Start ();
NewThread (() = Write ("T2") {IsBackground =true}. Start ();
Thread.Sleep (Timespan.fromseconds ( -));
}
StaticReaderWriterLockSlim RWL =NewReaderWriterLockSlim ();
Staticdictionary<int,int> items =Newdictionary<int,int> ();
StaticvoidRead ()
{
Console.WriteLine ("readind contents of a dictionary");
while(true)
{
Try
{
Rwl. EnterReadLock ();
foreach(varIteminchItems. Keys)
{
Thread.Sleep (Timespan.fromseconds (0.1));
Console.WriteLine (Items[item]);
}
}
finally
{
Rwl. Exitreadlock ();
}
}
}
StaticvoidWrite (stringThreadName)
{
while(true)
{
Try
{
intNewKey =NewRandom (). Next ( -);
Rwl. Enterupgradeablereadlock ();
if(!items. ContainsKey (NewKey))
{
Try
{
Rwl. Enterwritelock ();
Items[newkey] = NewKey;
Console.WriteLine ("New Key {0} is added to a dictionary by a {1}", NewKey, ThreadName);
}
finally
{
Rwl. Exitwritelock ();
}
}
Thread.Sleep (Timespan.fromseconds (0.1));
}
finally
{
Rwl. Exitupgradeablereadlock ();
}
}
}
}
Multithreaded 15-readerwriterlockslim