C#中的timer与线程使用
作者:qgbooooo 发布时间:2023-08-21 00:13:11
标签: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);
});
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
来源:https://blog.csdn.net/qqqgg/article/details/80234597


猜你喜欢
- 最近有一个项目要用到年份周期,用于数据统计图表展示使用,当中用到年份周期,以及年份周期所在的日期范围。当初设想通过已知数据来换算年份周期,经
- 本文实例为大家分享了Java实现斗地主游戏的具体代码,供大家参考,具体内容如下原理图:斗地主过程: 1、组合牌&nb
- 序列化与反序列化是.net程序设计中常见的应用,本文即以实例展示了.net实现序列化与反序列化的方法。具体如下:一般来说,.net中的序列化
- Java反射机制一、什么是反射机制 简单的来
- 这个其实很简单,思路是这样的,就是拿view的宽度,除以点的点的宽度+二个点 之间的间距,就可以算出大概能画出几个点
- 在这里,我们将用到finish(),简单介绍一下它的使用:finish()官方解析:Call this when your activity
- 本文实例讲述了C#实现对数组进行随机排序类。分享给大家供大家参考。具体如下:这个一个扩充C#随机数发生器的类,可以随机生成指定范围的数字,可
- 代码如下所示:package com.hoo.util; import java.awt.Color; import
- 本文所述实例实现WinForm自定义函数FindControl实现按名称查找控件的功能,在C#程序开发中有一定的实用价值。分享给大家供大家参
- 背景出现了一次生产事故,事情是这样的,我们有一个项目,Java访问数据库的框架使用的是MyBatis。然后一个业务员在系统中查询了一个订单,
- 问题之前研究了Java通过执行cmd命令从而触发Android打包的思路,但是发现Android打包成功之后,后面的代码逻辑就不走了(连输出
- 提几个问题,从问题中去了解去学习:他们之间有啥区别?如果我使用notify(),将通知哪个线程?我怎么知道有多少线程在等待,所以我可以使用n
- 1.Thread的构造方法package threadAPI;public class CreateThread { publi
- httpSecurity类似于spring security的xml配置文件命名空间配置中的<http>元素。它允许对特定的ht
- 废话不多说了,直接给大家贴java代码了。import java.awt.Color; import java.awt.Grap
- 前言Camera2是Android新的Camera框架,整体来讲Camera2为应用程序提供了许多标准接口,使更多的功能可以通过参数控制;但
- 这一篇网络爬虫的实现就要联系上大数据了。在前两篇java实现网络爬虫和heritrix实现网络爬虫的基础上,这一次是要完整的做一次数据的收集
- 本文实例讲述了Android TextView中文字通过SpannableString设置属性的方法。分享给大家供大家参考,具体如下:在An
- 前面有写到Spring+SpringMVC+MyBatis深入学习及搭建(二)——MyBatis原始Dao开发和mapper代理开发MyBa
- package TestList;import java.util.ArrayList;import java.util.Iterator;