c# – 告诉计时器对象以异步方式调用其“Elapsed”事件
发布时间:2020-12-16 01:37:42 所属栏目:百科 来源:网络整理
导读:我的应用程序中有时候需要手动调用我的计时器. 我尝试过以下方法: int originalInterval = t.Interval;t.Interval = 0;t.Interval = originalInterval; 但它并不一致. 我创建了一个新的计时器,继承自System.Timers.Timer,并公开了一个“Tick”方法 – 但问
我的应用程序中有时候需要手动调用我的计时器.
我尝试过以下方法: int originalInterval = t.Interval; t.Interval = 0; t.Interval = originalInterval; 但它并不一致. 我创建了一个新的计时器,继承自System.Timers.Timer,并公开了一个“Tick”方法 – 但问题是“Elapsed”事件然后同步触发. 当我使用新线程实现“Tick”时 – 结果再次不一致. 有没有更好的方法来实现它? 解决方法
我曾经遇到过同样的问题,所以我使用AutoResetEvent知道是否成功调用了Elapsed:
/// <summary> /// Tickable timer,allows you to manually raise a 'Tick' (asynchronously,of course) /// </summary> public class TickableTimer : System.Timers.Timer { public new event ElapsedEventHandler Elapsed; private System.Threading.AutoResetEvent m_autoResetEvent = new System.Threading.AutoResetEvent(true); public TickableTimer() : this(100) { } public TickableTimer(double interval) : base(interval) { base.Elapsed += new ElapsedEventHandler(TickableTimer_Elapsed); } public void Tick() { new System.Threading.Thread(delegate(object sender) { Dictionary<string,object> args = new Dictionary<string,object> { {"signalTime",DateTime.Now},}; TickableTimer_Elapsed(this,Mock.Create<ElapsedEventArgs>(args)); }).Start(); this.m_autoResetEvent.WaitOne(); } void TickableTimer_Elapsed(object sender,ElapsedEventArgs e) { m_autoResetEvent.Set(); if (this.Elapsed != null) this.Elapsed(sender,e); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |