Timer 在Try-Catch内停止计时器
不知道为什么这不起作用。我定义了一个计时器,它每2秒运行一个方法。在这种方法中,我有一个尝试。尝试执行此代码时,catch应禁用计时器,然后显示一个消息框。由于某些原因,我的消息框每2秒反复显示一次。为什么我的计时器不能禁用Timer 在Try-Catch内停止计时器,timer,try-catch,Timer,Try Catch,不知道为什么这不起作用。我定义了一个计时器,它每2秒运行一个方法。在这种方法中,我有一个尝试。尝试执行此代码时,catch应禁用计时器,然后显示一个消息框。由于某些原因,我的消息框每2秒反复显示一次。为什么我的计时器不能禁用 Timer timer1 = new Timer(); public MainForm() { timer1.Interval = 2000; timer1.Tick += new EventHandler(OnTi
Timer timer1 = new Timer();
public MainForm()
{
timer1.Interval = 2000;
timer1.Tick += new EventHandler(OnTimer);
timer1.Enabled = true;
//More code
}
private void OnTimer(object sender, EventArgs e)
{
try
{
//Code
}
catch (Exception)
{
MessageBox.Show("Message");
timer1.Enabled = false;
this.Dispose();
}
}
谢谢-杰森你的尝试毫无意义,因此没有任何东西会让你失败
如果你确实有一些代码在里面,你确定它会抛出一个异常,并命中捕获点吗?这将帮助你理解
Timer timer1 = new Timer();
public MainForm()
{
timer1.Interval = 2000;
timer1.Tick += new EventHandler(OnTimer);
timer1.Enabled = true;
//More code
}
private void OnTimer(object sender, EventArgs e)
{
try
{
throw new InvalidOperationException("Now the catch executes! Poof!");
}
catch (Exception)
{
MessageBox.Show("Message");
timer1.Enabled = false;
this.Dispose();
}
}
也许你是有意的
private void OnTimer(object sender, EventArgs e)
{
try
{
// code
}
catch (Exception)
{
MessageBox.Show("Message");
this.Dispose();
}
finally
{
timer1.Enabled = false;
}
}
我猜
MessageBox.Show(“Message”)
正在阻止执行timer1.Enabled=false代码>因为它是一个模式对话框。在显示模式对话框之前,请尝试禁用计时器,使其不会继续首先触发OnTimer回调:
private void OnTimer(object sender, EventArgs e)
{
try
{
// Code
}
catch (Exception)
{
timer1.Enabled = false;
MessageBox.Show("Message");
this.Dispose();
}
}
try块包含注释//code
,这意味着try中实际上有代码。您能否发布再现问题的最小代码示例(即用真实代码替换//code
)?对于//代码,很抱歉,但是try中的代码并不重要。我的问题是关于捕获的。谢谢,谢谢你的回复。李邦进是对的。MessageBox正在阻止计时器1。Enabled=false。完美!我知道这是一件愚蠢的事,我只是没有看到。非常感谢!!!