使用Timer的交叉线程错误处理表单

Tho*_*mas 5 c# error-handling exception winforms

我在我的一个窗体上设置了10秒的计时器.对于OnTimedEvent,我设置表格在时间结束后处理.但是似乎有一个错误

用户代码未处理InvalidOperationException.

跨线程操作无效:控制'notificationForm'从其创建的线程以外的线程访问.

错误就行了

protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }
Run Code Online (Sandbox Code Playgroud)

我的计时器事件的代码是

    private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        this.Dispose();
    }
Run Code Online (Sandbox Code Playgroud)

有人知道怎么修这个东西吗?谢谢!

Lar*_*ech 5

看起来您正在使用System.Timers.Timer.

尝试使用System.Windows.Forms.Timer代替并订阅该Tick事件。

如果您必须使用该计时器,您可以尝试将代码更改为:

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
   this.BeginInvoke((MethodInvoker)delegate { this.Dispose(); });
}
Run Code Online (Sandbox Code Playgroud)