System.Timers.Timer 服务器计时器

System.Timers.Timer 服务器计时器

1、针对服务器的服务程序,基于System.Threading.Timer,被设计并优化成能用于多线程环境。在这种情况下,应该确保事件处理程序不与 UI 交互。在asp.net中一般使用System.Timers.Timer。

2、继承自Compnent,公开了可以SynchronizingObject 属性,避免了线程池中无法访问主线程中组件的问题(模拟System.Windows.Forms.Timer单线程模式)。但是除非需要对事件的时间安排进行更精确的控制,否则还是应该改为使用 System.Windows.Forms.Timer。

3、AutoReset属性设置计时器是否在引发Elapsed事件后重新计时,默认为true。如果该属性设为False,则只执行timer_Elapsed方法一次。

4、System.Timers.Timer是多线程定时器,如果一个Timer没有处理完成,到达下一个时间点,新的Timer同样会被启动。所以,Timer比较适合执行不太耗时的小任务,若在Timer中运行耗时任务,很容易出现由于超时导致的多线程重入问题,即多个线程同时进入timer_Elapsed方法。

System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 500;
timer.SynchronizingObject = this;

timer.Elapsed+=new System.Timers.ElapsedEventHandler(timer_Elapsed);

timer.Start(); private void timer_Elapsed(Object source, Timers.ElapsedEventArgs e)
{
this.tbTimer.Text = value;
}
5、为了应对多线程重入问题。可以加锁,也可以增加标志位。 Interlocked.Exchange提供了一种轻量级的线程安全的给对象赋值的方法,所以使用Interlocked.Exchange给变量赋值。

int inTimer = 0;
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (Interlocked.Exchange(ref inTimer, 1) == 0)
{
Thread.Sleep(3000);
string currentThreadId = Thread.CurrentThread.ManagedThreadId.ToString();
this.Dispatcher.BeginInvoke(new Action(() =>
{
this.Label_Result.Content += currentThreadId + “,”;
}), null);
Interlocked.Exchange(ref inTimer, 0);
}
}

System.Timers.Timer和DispatcherTimer都是用于定时执行任务的计时器类,但它们在使用方式和适用场景上有所不同。 System.Timers.Timer是一个多线程计时器,适用于在后台线程执行周期性任务。它是基于底层的System.Threading.Timer实现的,可以在指定的时间间隔内重复执行任务。以下是一个使用System.Timers.Timer的示例: ```csharp static System.Timers.Timer Timer1 = new System.Timers.Timer(); static void Main() { Timer1.Interval = 1000; // 设置时间间隔为1秒 Timer1.Elapsed += new ElapsedEventHandler(PeriodicTaskHandler); // 绑定事件处理程序 Timer1.Start(); // 启动计时器 } static void PeriodicTaskHandler(object sender, ElapsedEventArgs e) { // 执行周期性任务的代码 } ``` DispatcherTimer是一个UI线程计时器,适用于在UI线程上执行周期性任务。它是基于WPF的Dispatcher对象实现的,可以在指定的时间间隔内重复执行任务,并且可以直接更新UI元素。以下是一个使用DispatcherTimer的示例: ```csharp private void StartTimer() { DispatcherTimer dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Tick += OnTimerHandler; // 绑定事件处理程序 dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); // 设置时间间隔为100毫秒 dispatcherTimer.Start(); // 启动计时器 } private void OnTimerHandler(object sender, EventArgs e) { string strTime = DateTime.Now.ToString("HH:mm:ss:fff"); // 获取当前时间 lbTime.Content = strTime; // 更新UI元素 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值