欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Winform基于多线程实现每隔1分钟执行一段代码

程序员文章站 2023-12-18 17:34:04
本文实例讲述了winform基于多线程实现每隔1分钟执行一段代码的方法,分享给大家供大家参考。具体实现方法如下: 1.定义相关的类timer.cs,代码如下: 复制代码...

本文实例讲述了winform基于多线程实现每隔1分钟执行一段代码的方法,分享给大家供大家参考。具体实现方法如下:

1.定义相关的类timer.cs,代码如下:

复制代码 代码如下:
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading;

namespace smis2013.dss.monitor
{
    public class mytimer
    {
        public delegate void elapsed(); //定义委托 
        public event elapsed onelapsed;

        private long _interval = 1000;
        public long interval
        {
            get { return _interval; }
            set { _interval = value; }
        }

        private bool _isstart = false;
        private thread _timerthread;
        public void start()
        {
            if (_isstart)
                return;

            _isstart = true;

            _timerthread = new thread(new threadstart(dotimer));
            _timerthread.start();
        }


        public void stop()
        {
            try
            {
                if (!_isstart)
                    return;

                _isstart = false;

                _timerthread.abort();
            }
            catch (exception e)
            { }
        }

        private void dotimer()
        {
            try
            {
                int last = environment.tickcount;
                while (_isstart)
                {
                    if (environment.tickcount - last > _interval)
                    {
                        if (onelapsed != null)
                            onelapsed();

                        last = environment.tickcount;
                      
                    }
                    thread.sleep(100);
                }


            }
            catch (exception e)
            { }
        }

    }
}

2.在主线程部分引用此类。在需要执行的event加入:

复制代码 代码如下:
private const int _interval =40000;
        private mytimer _timer;

  private void form1_load(object sender, eventargs e)
        {

            _timer = new mytimer();
            _timer.interval = _interval;
            _timer.start(); //开始
            _timer.onelapsed += timer_onelapsed;
        }
 void timer_onelapsed()
        {
            invoke(new action(() => 加入需要执行的event));
            //to do
        }

private void form1_formclosed(object sender, formclosedeventargs e)

{

//记得需要结束

if (_timer != null)

{

_timer.onelapsed -= timer_onelapsed;

_timer.stop();

}

}

希望本文所述对大家的c#程序设计有所帮助。

上一篇:

下一篇: