C# 在类中使用Timer定时器以及延时处理的方法

我们平时在C#中要用到定时功能时,有自带定时器,一般在定时器里面写函数就行了,现在需要在类里面写了一个定时器,不和界面绑定,一开始的时候感觉没什么思路,然后看了一下界面的设计代码,有了思路,还是很简单的

首先我们在界面上放一个定时器,看一下代码:

 this.timer1 = new System.Windows.Forms.Timer(this.components);
 this.timer1.Enabled = true;
 this.timer1.Interval = 2000;
 this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

我们用Timer类创建timer1这个实例,调用它的方法就好了,修改代码如下:

 public partial class Form1 : Form
    {
        private int i = 0;
        public Form1()
        {
            InitializeComponent();
            Timer timer1 = new Timer();
            timer1.Enabled = true;
            timer1.Interval = 1000;
            timer1.Tick += new System.EventHandler(this.timer1_Tick);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            i++;
            textBox1.Text += i + "S" + "\r\n";
        }

    }

效果如图所示:

 

有时候我们还会遇到另外一种情况,需要程序延时运行,尤其是像我做摄像头,需要摄像头在一个地方停留一段时间再继续运行的,使用上面的定时器方法是不行的,我在网上搜索了一个方法,很管用:

  public static bool Delay(int delayTime)
        {
            DateTime now = DateTime.Now;
            int s;
            do
            {
                TimeSpan spand = DateTime.Now - now;
                s = spand.Seconds;
                Application.DoEvents();
            }
            while (s < delayTime);
            return true;
        }

写一个循环验证一下:

 public void hh()
        {
            for (int i = 0; i < 5; i++)
            {
                textBox1.Text += "抓图" + i + "\r\n";
              if(Delay(5))
              {
                  continue;
              }
            }
        }

完美解决

posted @ 2017-12-14 16:19  StephenCurry  阅读(7917)  评论(0编辑  收藏  举报