2013-08-27 41 views
0

我在写一个需要与串口通信的程序。我主要关心的是防止碰撞,并确保不同时写入/读取不同的功能。在多线程间执行代码

首先,有一个系统定时器从开始开始,用于周期性地将数据写入到串行端口,并且还收听由给定的超时值的响应。因此,它会有一个已经完成的事件并完成工作。

其次,还有另外一个功能,具有较高优先级服务,将需要立即将数据写入到串行端口。

方案1. Elapsed事件烧成每次1分钟,并继续进行从未如果仍然从先前的一个或SendImmediately功能挂起。

场景2. 如果SendImmediately被调用,它将需要等待当前运行的OnTimedEvent完成。再次,OnTimedEvent的下一次运行将停止,直到SendIm立即完成。

问题。 如何在上一个或SendImmediately完成之前阻止OnTimedEvent的下一次运行?基本上,要防止它们之间的干扰。

我已经经历了一些问答&一去这里。有许多建议答案象下面这样:

  • 禁用和启用定时器
  • 的AutoResetEvent(2路信令)
  • ManualResetEvent的
  • Monitor.Enter/Monitor.Exit(锁定)
  • 队列
  • 睡眠/加入/任务。等待(阻止)

我没有坚实的fo因为每个人都有不同的情景,所以决定哪一种方法适合我或者适合我。非常感谢任何建议。

public System.Timers.Timer aTimer = new System.Timers.Timer(Properties.Settings.Default.Interval * 60 * 1000); 
    public bool InitialTimer(int interval, bool action) 
    { 
     aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
     aTimer.Interval = interval; 
     aTimer.Enabled = action; 
     GC.KeepAlive(aTimer); 
     return action; 
    } 

    public void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 
     // write something to serial port 
    } 
    public void WriteImmediately() 
    { 
     // write something to serial port 
    } 

回答

0

我会做一个'SerialComms'线程在生产者 - 消费者队列中等待超时。如果队列等待超时,SerialComms将执行轮询定时操作,然后返回队列等待。如果优先级较高的thred想要将某些内容写入端口,它可以对其消息进行排队,这样可以使SerialComms队列等待立即返回而不会超时,然后'SerialComms'代码可以执行写入缓冲区。

The high-priority writes are signaled onto the SerialComms thread 'immediately'. 
No explicit timer required. 
No possibility of the high-priority write interrupting an ongoing timed operation. 
No possibility of multiple timed operations stacking up or interrupting each other. 
Multiple high-priority writes can be queued up without any interference.