我正在使用Windows窗体启动System.Timers.Timer,每隔3秒触发一次事件。当我关闭表格时,这个过程会继续射击,这很好。当我重新打开表单以通过单击按钮btnSendOff_Click
停止计时器时,会出现问题。
System.Timers.Timer sendTimer = new System.Timers.Timer();
sendTimer.Elapsed += new ElapsedEventHandler(sendProcessTimerEvent);
sendTimer.Interval = 3000;
private void sendProcessTimerEvent(object sender, EventArgs e)
{
MessageBox.Show("Send 3 sec");
}
private void btnSendOn_Click(object sender, EventArgs e)
{
sendTimer.Start();
}
private void btnSendOff_Click(object sender, EventArgs e)
{
sendTimer.Stop();
}
此表单上将有更多异步计时器。当我重新打开表单时,如何停止此计时器?
答案 0 :(得分:2)
如果窗体关闭后需要继续运行,则每次创建窗体的新实例时,窗体都不应创建新的计时器。您声明计时器的方式,每次创建表单时它将创建另一个。您应该将计时器放在不同的表单上或在某个全局模块中声明它,并且只使表单激活或停用计时器。如果表单在表单关闭时需要继续运行,则表单不应该是拥有或创建计时器的表单。如果在窗体关闭时计时器不需要继续运行,那么您应该使用Forms.Timer而不是System.Timer。
修改:添加示例代码
static class Program
{
public static System.Timers.Timer sendTimer;
public static System.Text.StringBuilder accumulatedText;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
sendTimer = new System.Timers.Timer();
accumulatedText = new System.Text.StringBuilder("Started at " + DateTime.Now.ToLongTimeString() + Environment.NewLine);
sendTimer.Interval = 3000;
sendTimer.Elapsed += new System.Timers.ElapsedEventHandler(sendProcessTimerEvent);
Application.Run(new MainForm());
}
static void sendProcessTimerEvent(object sender, System.Timers.ElapsedEventArgs e)
{
accumulatedText.AppendLine("Pinged at " + DateTime.Now.ToLongTimeString());
}
}
class MainForm : Form
{
ToolStrip mainToolStrip = new ToolStrip();
public MainForm()
{
mainToolStrip.Items.Add("Log Control").Click += new EventHandler(MainForm_Click);
Controls.Add(mainToolStrip);
}
void MainForm_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
frm.ShowDialog();
}
}
class Form1 : Form
{
private Button button1 = new Button();
private TextBox text1 = new TextBox();
public Form1()
{
button1.Dock = DockStyle.Bottom;
button1.Text = Program.sendTimer.Enabled ? "Stop": "Start";
button1.Click += new EventHandler(button1_Click);
text1 = new TextBox();
text1.Dock = DockStyle.Fill;
text1.Multiline= true;
text1.ScrollBars = ScrollBars.Vertical;
text1.Text = Program.accumulatedText.ToString();
Controls.AddRange(new Control[] {button1, text1});
}
void button1_Click(object sender, EventArgs e)
{
Program.sendTimer.Enabled = !Program.sendTimer.Enabled;
button1.Text = Program.sendTimer.Enabled ? "Stop" : "Start";
}
}