thread: heartbeat and reset
I am nwe to C# thread. I have a heartbeat class which will run in a thread
like this:
Class Heartbeat
{
private int miRate;
private int miCount = 0;
public Heartbeat(int Rate) { this.miRate = Rate; }
public void Start() {
while ( true )
{
Thread.Sleep( 1 ) // sleep 1 second
if ( this.miCount++ >= this.miRate )
Console.WriteLine("Heartbeat {0}", DateTime.Now);
else
this.miCount = 0;
}
}
public void Reset()
{
this.miCount = 0;
}
}
After I create a Heartbeat obj and start it in a thread, I do need to call
Reset sometimes to reset the heartbeat. However, it does not run correctly.
What happens if the thread is in sleep mode while calling its Reset mothod?
Is Reset still accessible? How can I reset the heartbeat correctly?
D. Chu
Re: thread: heartbeat and reset
"David Chu" <chud@hotmail.com> wrote:
>
>I am nwe to C# thread. I have a heartbeat class which will run in a thread
>like this:
>
>Class Heartbeat
>{
> private int miRate;
> private int miCount = 0;
>
> public Heartbeat(int Rate) { this.miRate = Rate; }
>
> public void Start() {
> while ( true )
> {
> Thread.Sleep( 1 ) // sleep 1 second
> if ( this.miCount++ >= this.miRate )
> Console.WriteLine("Heartbeat {0}", DateTime.Now);
> else
> this.miCount = 0;
> }
> }
>
> public void Reset()
> {
> this.miCount = 0;
> }
>}
>
>After I create a Heartbeat obj and start it in a thread, I do need to call
>Reset sometimes to reset the heartbeat. However, it does not run correctly.
>What happens if the thread is in sleep mode while calling its Reset mothod?
>Is Reset still accessible? How can I reset the heartbeat correctly?
>
>D. Chu
Is start you thread function and your calling reset from another thread?
If this is the caese Reset is accessible but there are threading issues to
consider. You need to look into synchronzation objects if you wnat you inter
thread call to behave.
This would work....
public class Beat
{
AutoResetEvent reset = new AutoResetEvent(false);
int timeOut = 0;
Beat(int timeOut)
{
this.timeOut = timeOut;
}
public void ThreadFunc()
{
while(true)
reset.WaitOne(timeOut, false);
}
public void Reset()
{
reset.Set();
}
}
but there is the System.Timers.Timer class that is made for this sort of
thing.
Brian