当前位置: 代码迷 >> C# >> C#使用System.Timers封锁再打开后发现重复执行
  详细解决方案

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

热度:207   发布时间:2016-05-05 02:48:29.0
C#使用System.Timers关闭再打开后发现重复执行
使用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);
        }
    }
}

------解决思路----------------------
        public Form1()
        {
            InitializeComponent();
            time.Elapsed += new ElapsedEventHandler(t);  //挪到这里
            time.Interval = 1000;
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            sta = 1;
            time.Start();
        }
  相关解决方案