我在我的一个窗口窗体上设置了一个 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/