tags:

views:

29

answers:

1

I have a win form that is using a System.Timers.Timer. When the timer executes it updates a variable on the mainForm. I am getting an exception telling me that mainForm has been disposed. What am I doing wrong. If I take out updating the variable the program runs fine. If I try and read the variable and post it to a message box, everything works fine. Only when I try and change the value of the variable from the timer event handler do I get the exception. What is going on?

//works
private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
       MessageBox.Show(myVarFromMainForm);
    }
//does not work
private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        myVariableFromMainForm = 10;
    }
A: 

It isn't very likely that the code as posted bombs on ObjectDisposed. However, getting the exception is unsurprising when you use System.Timers.Timer. You have to make sure that the timer is shut down before the form closes. Not doing so allows the Elapsed event to run when the form object is dead.

The bigger problem with that is that it is practically impossible to guarantee that the timer is actually stopped. There is an inevitable race condition, the Elapsed event may have already been scheduled to run while you are stopping the timer. There are various, unpleasant, things you can do about that. But before you go there, make sure that System.Windows.Forms.Timer doesn't solve your problem. It is a synchronous timer, it will never Tick after the form closes. It also avoids the kind of nasty threading problems you can run into when you access class members in the Elapsed event without using the lock statement.

Hans Passant