如何启动计时器以响应非UI事件(如串行端口活动)



从主UI(例如通过按钮)启动时,计时器(System.Windows.Forms)确实会正常启动。但是,当信号来自另一个地方时,我无法完全启动它—在这种情况下,来自串行端口的事件。

我知道这里需要BeginInvoke/Invoke和委托,但作为一名新程序员,我不明白,我需要一些帮助。

//button in the main UI. Fires up the timer.
private void button1_Click(object sender, EventArgs e)
{
     timer1.Enabled = true; //this one here works perfectly
}
//an event handler for a serial port event, does NOT fire up the timer.
public void SomethingHappenedWithTheSerialPort(object sender, EventArgs eventrgs)
{
     timer1.Enabled = true; //does NOT work at all. I don't know how to use Invoke.
}

编辑:这就是我打开端口并监听PinChanged事件的方式。

int baudrate = 9600;
int databits = 8;
Main mainhandler = new Main();
System.IO.Ports.SerialPort ComPorttoUse = new SerialPort(Properties.Settings.Default.COMPortToUse, baudrate, Parity.None, databits, StopBits.One);
ComPorttoUse.Handshake = Handshake.None;
ComPorttoUse.PinChanged += new SerialPinChangedEventHandler(mainhandler.PortDetectWhatPinChanged);
ComPorttoUse.Open();
//an event handler for a serial port event, does NOT fire up the timer.
public void SomethingHappenedWithTheSerialPort(object sender, EventArgs eventrgs)
{
     timer1.Enabled = true; //does NOT work at all. I don't know how to use Invoke.
}

此事件处理程序从未被调用,因为您似乎没有将其订阅到SerialPort对象的任何事件。相反,您已经为PinChanged事件订阅了一个名为PortDetectWhatPinChanged的处理程序方法:

ComPorttoUse.PinChanged += new SerialPinChangedEventHandler(mainhandler.PortDetectWhatPinChanged);

如果您希望调用SomethingHappenedWithTheSerialPort,则需要将其"添加"到事件中:

ComPorttoUse.PinChanged += new SerialPinChangedEventHandler(SomethingHappenedWithTheSerialPort);
//                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                  ^
//                         note: not required, the compiler can usually infer this bit.

并且您的处理程序方法必须具有与PinChanged事件的签名兼容的签名,因此您需要将其更改为:

public void SomethingHappenedWithTheSerialPort(object sender, SerialPinChangedEventArgs e)
{                                                          // ^^^^^^^^^^^^^^^^^^^^^^^^^
    timer1.Enabled = true;                                 //    this needs changing!
}

尝试以下代码。

Application.Current.Dispatcher.BeginInvoke((Action)(() =>{timer1.Enabled = true;}));

阅读MSDN中关于dispatcher的内容。这将帮助你理解它。

https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.begininvoke%28v=vs.110%29.aspx

相关内容

  • 没有找到相关文章

最新更新