zoukankan      html  css  js  c++  java
  • 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" + "
    ";
            }
    
        }

    效果如图所示:

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

      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 + "
    ";
                  if(Delay(5))
                  {
                      continue;
                  }
                }
            }

    完美解决

  • 相关阅读:
    mysql 用户表结构设计,第三方登录
    linux centOS服务器部署ssh,免密码登陆linux
    linux SSH免密码登录远程服务器
    java反射机制学习笔记
    jvm知识
    类继承相关信息
    拦截器和过滤器的执行顺序和区别
    实现Map按key或按value排序
    喜欢的句子
    sql 性能优化相关--总结别人的总结,未做验证,先归纳
  • 原文地址:https://www.cnblogs.com/Liu30/p/8038346.html
Copyright © 2011-2022 走看看