Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross Thread error disposing form with Timer

I have a timer set for 10 seconds at one of my windows form. And for the OnTimedEvent, i set for the form to be disposed after the time has been up. However there seems to be an error of

InvalidOperationException was unhandled by user code.

Cross-thread operation not valid: Control 'notificationForm' accessed from a thread other than the thread it was created on.

The error was on the line

protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

the code for my timer event is

    private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        this.Dispose();
    }

Anyone know how to fix this? thanks!

like image 259
Thomas Avatar asked Dec 16 '11 16:12

Thomas


2 Answers

It looks like you are using the System.Timers.Timer.

Try using the System.Windows.Forms.Timer instead and subscribe to the Tick event.

If you have to use that Timer, you could try changing your code to this:

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
   this.BeginInvoke((MethodInvoker)delegate { this.Dispose(); });
}
like image 196
LarsTech Avatar answered Sep 16 '22 19:09

LarsTech


Or just:

this.Invoke((Action)(() => { this.Dispose(); }));

You can do this in one line:

timer1.Tick += (_, __) => { this.Invoke((Action)(() => { this.Dispose(); })); };
like image 30
Niklas Avatar answered Sep 19 '22 19:09

Niklas