Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Threading.Timer callback is never called

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?

like image 365
docaholic Avatar asked Dec 01 '22 18:12

docaholic


1 Answers

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.

like image 136
Lasse V. Karlsen Avatar answered Dec 29 '22 11:12

Lasse V. Karlsen