我想构建一个Windows服务,它应该在不同的时间执行不同的方法。这与准确性无关。
我使用System.Timers.Timer,在事件处理程序方法中使用计数器来调节要执行的不同方法。到目前为止,这样做得很好。
所有的方法都访问COM端口,因此需要仅授予一种方法访问权限。但由于方法可能需要一些时间才能完成,计时器可能会再次滴答声并希望在COM端口仍被占用时执行另一个方法。在这种情况下,事件可以且应该被忽略。
简化为一个方法,我的ElapsedEventHandler方法看起来像以下内容(省略了try-catch和不同的方法)
注意:虽然这在我的Win7 x64上运行得非常完美,但在安装了几乎完全相同软件的Win7 x86机器上,当要执行的方法需要很长时间时,它会遇到困难。计时器不会再次滴答声,也不会抛出异常。什么都没有!我的问题是:我是否正确地处理了访问控制和计时器部分,以便我可以专注于其他事情?我只是不太熟悉计时器和特别是线程。
非常感谢您的帮助!
任何帮助都将不胜感激!
private static int m_synchPoint=0;
private System.Timers.Timer timerForData = null;
public MyNewService()
{
timerForData = new System.Timers.Timer();
timerForData.Interval = 3000;
timerForData.Elapsed += new ElapsedEventHandler(Timer_tick);
}
//Initialize all the timers, and start them
protected override void OnStart(string[] args)
{
timerForData.AutoReset = true;
timerForData.Enabled = true;
timerForData.Start();
}
//Event-handled method
private void Timer_tick(object sender, System.Timers.ElapsedEventArgs e)
{
////safe to perform event - no other thread is running the event?
if (System.Threading.Interlocked.CompareExchange(ref m_synchPoint, 1, 0) == 0)
{
//via different else-ifs basically always this is happening here, except switching aMethod,bMethod...
processedevent++;
Thread workerThread = new Thread(aMethod);
workerThread.Start();
workerThread.Join();
m_synchPoint=0;
}
else
{
//Just dismiss the event
skippedevent++;
}
}
非常感谢您的帮助!
任何帮助都将不胜感激!
workerThread.Start
然后紧接着调用workerThread.Join
?这样做没有任何好处,因为计时器线程只会等待新线程完成。直接执行aMethod
,避免额外开启一个线程的开销。 - Jim Mischel