停止计时器在另一个班级

时间:2016-03-01 18:00:03

标签: c# events timer

我有一个程序可以通过串口发送和接收消息。

我有这个Sender类:

  public class Sender
  {
    private System.Timers.Timer _responseTimer;

    public Sender(SerialPort sp)
    {
      _serialPort = sp;
      _responseTimer = new System.Timers.Timer(2000);
    }

    public void Attach(ISenderObserver iso)
    {
      _responseTimer.Elapsed += new ElapsedEventHandler(iso.ResponseTooSlowEvent);
    }

    public void SendCommand(String command)
    {
       //start response timeout timer
      _responseTimer.AutoReset = false;
      _responseTimer.Enabled = true;
      _serialPort.Write(command);
    }
  }

然后我有这个接收课:

  public class Receiver : ISenderObserver
  {
    private static bool _continue;
    private static SerialPort _serialPort;
    private Thread _receiveThread;

    public Receiver(SerialPort sp)
    {
      _serialPort = sp;
      _continue = true;
      _serialPort.Open();
      //Start the receiving thread
      _receiveThread = new Thread(Receive);
      _receiveThread.Start();
    }

    public void Receive()
    {
      while (_continue)
      {
        String receivedMessage = _serialPort.ReadLine();
        //parse received message
      }
    }

    public void ResponseTooSlowEvent(object source, System.Timers.ElapsedEventArgs e)
    {
      Console.Write("\nToo Slow!");
    }
  }

这个界面:

  public interface ISenderObserver
  {
    void ResponseTooSlowEvent(object source, ElapsedEventArgs e);
  }

他们在主控制器中被这样调用:

  sender = new Sender(_serialPort);
  receiver = new Receiver(_serialPort);
  sender.Attach(receiver);

计时器的原因是我希望程序在等待一段时间后中止等待某个消息,从而避免在断开连接时出现死锁。

因此我希望尽快在Receiver-class中停止计时器:

String receivedMessage = _serialPort.ReadLine();

结束了。

如何在没有依赖关系的情况下执行此操作?

0 个答案:

没有答案