My System.Threading.Timer (which has a callback) never fires reliably. This is part of my programming assignment where I input the amount of time the timer is supposed to run from a textbox.
The timer is declared like this:
System.Threading.Timer timer = new System.Threading.Timer(WorkerObject.callback, null, delay, Timeout.Infinite);
And the delay is the simply an int
describing the delay for the callback to fire the first time (it is only supposed to fire once).
The callback method is like this:
public static void callback(Object stateinfo)
{
stop = true;
}
And all that does is set a flag to true which stops a loop (which is being run by a thread on a ThreadPool, in effect, stopping the thread).
The loop looks like this:
while (!stop)
{
currentTextbox.Invoke(new Action(delegate()
{
currentTextbox.AppendText((counter++) + Environment.NewLine);
currentTextbox.Update();
}));
}
My problem is that the stop
variable is always false for any delay over 5000 milliseconds. Is there a way to "force" the callback to always fire?
You need to hold on to the reference to the timer.
Most likely the timer object is being garbage collected, which will run its finalizer, stopping the timer.
So hold on to the reference for as long as you need the timer to be alive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With