【发布时间】:2012-08-15 04:29:23
【问题描述】:
是否有任何可能在 myForm_FormClosing 之后调用 timer_Tick 在下面的代码中。
如果有机会:是否足以在 myForm_FormClosing 中调用 timer.Stop() 以避免在 myForm_FormClosing 之后调用 timer_Tick?
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace Test
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
class MyForm : Form
{
private IContainer components;
private Timer timer;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
public MyForm()
{
components = new Container();
timer = new Timer(components);
timer.Interval = 50;
timer.Tick += timer_Tick;
timer.Enabled = true;
FormClosing += myForm_FormClosing;
}
private void timer_Tick(object sender, EventArgs e)
{
}
private void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
}
}
}
更新: 在收到一些提示(感谢您的帮助)之后,我基本上选择了以下代码来实现我想要的。 请不要在调用 myForm_FormClosing 之后仍然可以调用 timer1_Tick! 这个解决方案只是引入了一个标志(我称之为 doWork),它会在调用 myForm_FormClosing 后停止 timer1_Tick 内的代码执行。
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace Test
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
class MyForm : Form
{
private IContainer components;
private Timer timer;
private bool doWork = true;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
public MyForm()
{
components = new Container();
timer = new Timer(components);
timer.Interval = 50;
timer.Tick += timer_Tick;
timer.Enabled = true;
FormClosing += myForm_FormClosing;
}
private void timer_Tick(object sender, EventArgs e)
{
if (doWork)
{
//do the work
}
}
private void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
doWork = false;
}
}
}
【问题讨论】:
-
是的,是的。如果 myForm_FormClosing 将是一个紧张的过程,请确保尽早停止计时器。此外,如果您取消关闭,请确保在必要时重新启动计时器。
-
@PowerRoy 是的,我已经尝试过了。在 myForm_FormClosing 之后没有调用 timer_Tick。但这并不能保证没有机会。
-
@J-Torres 感谢您的回答。但是你能解释一下为什么答案是肯定的。有没有这方面的文件。 (我没有为那个特殊情况找到任何东西。)
-
OP,@JPAlioto 提供了一个很好的例子来说明这种情况是如何发生的。
-
@JTorres 感谢您指出这一点。