Cross error filtering when using a timer

I have a timer set to 10 seconds in one of my windows. And for OnTimedEvent, I set for a form that will be deleted after a while. However, it seems to be a mistake

InvalidOperationException failed to process user code.

Cross-threading is not valid: the 'notificationForm' control is accessible from a thread other than the thread in which it was created.

The error was on the line.

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

code for my timer event

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

Does anyone know how to fix this? thank!

+5
source share
4 answers

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

System.Windows.Forms.Timer Tick.

, :

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
   this.BeginInvoke((MethodInvoker)delegate { this.Dispose(); });
}
+4
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    this.Invoke(new Action(() => this.Dispose()));
}

+2

:

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

:

timer1.Tick += (_, __) => { this.Invoke((Action)(() => { this.Dispose(); })); };
+1

, , , . , dispose , .

, , , .

void OnTick()
{
    if (InvokeRequired)
        Invoke(new MethodInvoker(OnTick));
    else
    {
        Dispose();
    }
}
+1

All Articles