C#中的timer与线程使用

 更新时间:2022年08月12日 11:18:30   作者:qgbooooo  
这篇文章主要介绍了C#中的timer与线程使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

C#的timer与线程使用

卡顿怎么处理,多线程。多线程比timer好读。看看timer和线程的关系。

timer有3种

1.winform 下的timer。就是拖控件到UI上的那个timer.   

源文件在这个路径下C:\Windows\Microsoft.NET\Framework64\v4.0.30319

namespace System.Windows.Forms
{
    // 摘要:    实现按用户定义的时间间隔引发事件的计时器。 此计时器最宜用于 Windows 窗体应用程序中,并且必须在窗口中     使用。
    [DefaultEvent("Tick")]
    [DefaultProperty("Interval")][SRDescriptionAttribute("DescriptionTimer")][ToolboxItemFilter("System.Windows.Forms")]
    public class Timer : Component
}

启动timer代码如下:  

[SRCategory("CatBehavior")]
    [DefaultValue(false)]
    [SRDescription("TimerEnabledDescr")]
    public virtual bool Enabled
    {
        get
        {
            if (this.timerWindow == null)
            {
                return this.enabled;
            }
            return this.timerWindow.IsTimerRunning;
        }
        set
        {
            lock (this.syncObj)
            {
                if (this.enabled != value)
                {
                    this.enabled = value;
                    if (!base.DesignMode)
                    {
                        if (value)
                        {
                            if (this.timerWindow == null)
                            {
                                this.timerWindow = new TimerNativeWindow(this);
                            }
                            this.timerRoot = GCHandle.Alloc(this);
                            this.timerWindow.StartTimer(this.interval);
                        }
                        else
                        {
                            if (this.timerWindow != null)
                            {
                                this.timerWindow.StopTimer();
                            }
                            if (this.timerRoot.IsAllocated)
                            {
                                this.timerRoot.Free();
                            }
                        }
                    }
                }
            }
        }
    }

最终调用了this.timerWindow.StartTimer(this.interval); 源码如下。

可见,最终调用的是系统的timer?系统是有定时器的。Ucos上,就有32个定时器,当然也可以开线程。

他们是不同的概念。windows 也差不多吧。这些定时器应该与CPU有关。

public void StartTimer(int interval)
    {
        if (this._timerID == 0 && !this._stoppingTimer && this.EnsureHandle())
        {
            this._timerID = (int)SafeNativeMethods.SetTimer(new HandleRef(this, base.Handle), TimerNativeWindow.TimerID++, interval, IntPtr.Zero);
        }
    }

2.  public sealed class Timer : MarshalByRefObject, IDisposable   System.Threading.Timer

    public Timer(TimerCallback callback)
    {
        int dueTime = -1;
        int period = -1;
        StackCrawlMark stackCrawlMark = StackCrawlMark.LookForMyCaller;
        this.TimerSetup(callback, this, (uint)dueTime, (uint)period, ref stackCrawlMark);
    }
 
    [SecurityCritical]
    private void TimerSetup(TimerCallback callback, object state, uint dueTime, uint period, ref StackCrawlMark stackMark)
    {
        if (callback == null)
        {
            throw new ArgumentNullException("TimerCallback");
        }
        this.m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, ref stackMark));
    }
 
    [SecurityCritical]
    internal static void Pause()
    {
        TimerQueue.Instance.Pause();
    }
 
    [SecurityCritical]
    internal static void Resume()
    {
        TimerQueue.Instance.Resume();
    }

这里是TimerQueue 队列的操作。既然在Threading 命名空间下,可能与线程有关。他在的dll 是 mscorlib.

3.  System.Timers.Timer,  在system.dll中。  只是对 System.Threading.Timer的封装。

    [TimersDescription("TimerEnabled")]
    [DefaultValue(false)]
    public bool Enabled
    {
        get
        {
            return this.enabled;
        }
        set
        {
            if (base.DesignMode)
            {
                this.delayedEnable = value;
                this.enabled = value;
            }
            else if (this.initializing)
            {
                this.delayedEnable = value;
            }
            else if (this.enabled != value)
            {
                if (!value)
                {
                    if (this.timer != null)
                    {
                        this.cookie = null;
                        this.timer.Dispose();
                        this.timer = null;
                    }
                    this.enabled = value;
                }
                else
                {
                    this.enabled = value;
                    if (this.timer == null)
                    {
                        if (this.disposed)
                        {
                            throw new ObjectDisposedException(base.GetType().Name);
                        }
                        int num = (int)Math.Ceiling(this.interval);
                        this.cookie = new object();
                        this.timer = new System.Threading.Timer(this.callback, this.cookie, num, this.autoReset ? num : (-1));
                    }
                    else
                    {
                        this.UpdateTimer();
                    }
                }
            }
        }
    }

4.使用:

void Application_Start(object sender, EventArgs e)
    {
        // 在应用程序启动时运行的代码
        if (timer != null)
        {
            timer.Stop();
            timer.Close();
            timer = null;
        }
        int Interval = 3600000;//6 hours 
        timer = new System.Timers.Timer(Interval);//十分钟  
        timer.Elapsed += SendSMS.Send_ticker;
        timer.Interval = Interval;
        timer.Enabled = true;
        timer.Start();
    }

C#新线程延时

开启一个新线程

在这个线程中,进行任务排队。

任务1完成后,等待延时200ms,再运行任务2

 private void Timer1_Tick(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            Task.Run(() =>
            {
            
                this.Invoke( new Action( () => 
                {
                    listBox1.Items.Add("进中断"+DateTime.Now.ToString() + "\r\n");
                }));
                //RS485.Set_io(7);//ok
                //RS485.Rest_io(7);//ok
                if (i > 8) i = 0;
                RS485.Set_io(i++);//ok
                this.Invoke(new Action(() =>
                {
                    listBox1.Items.Add("第1次输出" + DateTime.Now.ToString() + "\r\n");
                }));
 
 
                Thread.Sleep(200);
                RS485.Rest_io((ushort)(i - 2));//ok                                           
                this.Invoke(new Action(() =>
                {
                    listBox1.Items.Add("第2次输出" + DateTime.Now.ToString() + "\r\n");
                }));
 
 
                Thread.Sleep(200);
                //RS485.Read_io_out(0,8);//ok
                RS485.Read_io_in(0, 8);//ok
                this.Invoke(new Action(() =>
                {
                    listBox1.Items.Add("第3次输出" + DateTime.Now.ToString() + "\r\n");
                }));
                //RS485.Read_io_Reg(0,4);//
                //RS485.Read_io_Regs(0, 6);//
                Thread.Sleep(200);
            });
        }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。 

相关文章

  • C#实现数组元素的数据类型转换方法详解

    C#实现数组元素的数据类型转换方法详解

    这篇文章主要为大家介绍了C#中一维数组如何快速实现数组元素的数据类型的转换,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2022-04-04
  • 利用WPF实现Windows屏保的制作

    利用WPF实现Windows屏保的制作

    屏保程序的本质上就是一个Win32 窗口应用程序。本文将利用WPF实现Windows屏保的制作,文中的示例代码简洁易懂,对我们学习WPF有一定帮助,感兴趣的可以了解一下
    2022-07-07
  • C#灰度化图像的实例代码

    C#灰度化图像的实例代码

    灰度化一幅图像就是将图像的色彩信息全部丢掉,将24位的位图信息,用8位来表示,灰度图共有256级灰度等级,也就是将24位位图的一点如(255,255,255)转换成255,所以R,G,B三个值所乘的系数和为1
    2013-09-09
  • C# 泛型编译特性对性能的影响小结

    C# 泛型编译特性对性能的影响小结

    C#作为一种强类型语言,具有丰富的泛型支持,允许开发者编写可以应对不同数据类型的通用代码,这篇文章主要介绍了C# 泛型编译特性对性能的影响 ,需要的朋友可以参考下
    2023-11-11
  • C#中volatile与lock用法

    C#中volatile与lock用法

    这篇文章主要介绍了C#中volatile与lock用法,较为详细的分析了C#中volatile与lock的适用情况及用法实例,具有一定的参考借鉴价值,需要的朋友可以参考下
    2014-10-10
  • C#线程倒计时器源码分享

    C#线程倒计时器源码分享

    这篇文章主要为大家分享了C#线程倒计时器源码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • C#字符串与数值类型、字节数组的互相转换实战案例

    C#字符串与数值类型、字节数组的互相转换实战案例

    最近由于编程的需要,对C#的类型转换做了一些研究,下面这篇文章主要给大家介绍了关于C#字符串与数值类型、字节数组的互相转换的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-06-06
  • Unity之绕轴进行旋转的操作

    Unity之绕轴进行旋转的操作

    这篇文章主要介绍了Unity之绕轴进行旋转的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-04-04
  • C#常用目录文件操作类实例

    C#常用目录文件操作类实例

    这篇文章主要介绍了C#常用目录文件操作类,实例分析了C#针对目录的读取、检测及查找等相关操作技巧,非常具有实用价值,需要的朋友可以参考下
    2015-03-03
  • C#线程 BeginInvoke和EndInvoke使用方法

    C#线程 BeginInvoke和EndInvoke使用方法

    本文开始C#线程系列讲座之一,即BeginInvoke和EndInvoke的使用方法,需要的朋友可以参考下
    2013-05-05

最新评论