c# - Cross Thread错误处理形式与Timer

标签 c# winforms exception error-handling

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

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.

在线上有错误

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

我的定时器事件的代码是

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

有人知道怎么解决吗?谢谢!

最佳答案

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

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

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

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

关于c# - Cross Thread错误处理形式与Timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8537477/

相关文章:

java - 关于try-catch的问题

haskell - GHCi 中定义的函数中的非穷尽模式

c# - 从源数组中选择给定范围的索引

c# - WinForms中常见的 "Drag and Drop"图标如何实现

c# - 如何使用组合框中的字典隐藏 UI 输出中的方括号?

c# - 数据 GridView Winforms : FullRowSelect current cell still visible

java - 获取未处理的异常类型格式错误的 url 异常

c# - List.AddRange 内联声明

c# - 如何在 C# 中读取 SQL 二进制字段

c# - 使用 .NET 4 MVC 3 和 jQuery 更新 DIV