• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

我们平时在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;
              }
            }
        }

完美解决


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap