C#使用System.Timers关闭再打开后发现重复执行

Felix_newComer 2015-09-27 11:05:03
使用System.Timers,两个按钮,一个开始,一个停止。
点击开始,执行一些简单操作。
点击停止,定时器stop。
操作流程:
1、点击开始,可以正常的输出,点击关闭,可以正常停止。
2、再次点击开始,发现输出两次,点击关闭,可以正常停止。
3、第3次点击开始,输出三次...
4、第4次.......
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.Threading;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int flag = 0;
int sta = -1;
private System.Timers.Timer time = new System.Timers.Timer();
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
sta = 1;
time.Elapsed += new ElapsedEventHandler(t);
time.Interval = 1000;
time.Start();
}
public void t(object o, EventArgs e)
{
if (sta == 1)
{
time.Stop();
SetText("HelloWorld!");
Thread.Sleep(500);
time.Start();
}
else
{
}
}

private void button2_Click(object sender, EventArgs e)
{
time.Stop();
sta = 0;
}
public void SetText(String s)
{
this.Invoke(new Action<string>((x) =>
{
flag += 1;
textBox2.Text = flag.ToString();
textBox1.Text += x;
}), s);
}
}
}
...全文
465 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Felix_newComer 2015-09-27
  • 打赏
  • 举报
回复
引用 1 楼 Forty2 的回复:
        public Form1()
        {
            InitializeComponent();
            time.Elapsed += new ElapsedEventHandler(t);  //挪到这里
            time.Interval = 1000;
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            sta = 1;
            time.Start();
        }
非常感谢!
ajianchina 2015-09-27
  • 打赏
  • 举报
回复
上面是知其然 你加一次就累计执行一次 这是所以然
Forty2 2015-09-27
  • 打赏
  • 举报
回复
        public Form1()
        {
            InitializeComponent();
            time.Elapsed += new ElapsedEventHandler(t);  //挪到这里
            time.Interval = 1000;
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            sta = 1;
            time.Start();
        }

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧