I have 2 thread (in printer and in counter class).the counter class updates the property in storage and printer prints it.Now i want to print the updated values by counter only once. so how do i stop the execution of my printer thread after printing the last updated number. It prints the last number sometimes once or sometimes more than once. Basically what I need is to update a property and every time that property is updated I need to print the updated value on the console and the printer thread doesn't know the no of updates that are going to take place. So it should stop as and when the updating thread stops updating.
The code is like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Threads
{
class Storage
{
static int _number;
public readonly static object LockNumber = new object();
public static int Number
{
get
{
lock(LockNumber)
{
Monitor.Pulse(LockNumber);
return _number;
}
}
set
{
lock(LockNumber)
{
_number = value;
Monitor.Pulse(LockNumber);
Monitor.Wait(LockNumber);
}
}
}
}
class Counter
{
public Thread t = new Thread(new ThreadStart(CounterFunction));
public Counter()
{
t.Start();
}
public static void CounterFunction()
{
for (int i = 0; i < 25; i++)
{
Storage.Number = i;
}
}
}
class Printer
{
public Thread t1 = new Thread(new ThreadStart(Print));
public Printer()
{
t1.Start();
}
public static void Print()
{
while (true)
{
Console.WriteLine("Number is " + Storage.Number);
}
}
}
class Check
{
static void Main()
{
Storage s1 = new Storage();
Counter c = new Counter();
Printer p = new Printer();
c.t.Join();
if (!c.t.IsAlive)
{
p.t1.Abort();
}
Thread.Sleep(10000);
}
}
}