C#中无法在串口serialPort1_DataReceived启动定时器的解决方法
这里的串口名是serialPort1,定时器名是timerRxInterval
方法1——修改启动方法
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Invoke((MethodInvoker)delegate
{
timerRxInterval.Start();
});
}
private void timerRxInterval_Tick(object sender, EventArgs e)
{
Console.WriteLine($"enter timerRxInterval_Tick");
timerRxInterval.Stop();
}
方法2——更改计时器的类型
删除显示界面的定时器
System.Timers.Timer timerRxInterval= new System.Timers.Timer(100);
timerRxInterval.Elapsed += new ElapsedEventHandler(timerRxInterval_Tick);
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
timerRxInterval.Start();
}
private void timerRxInterval_Tick(object sender, EventArgs e)
{
Console.WriteLine($"enter timerRxInterval_Tick");
timerRxInterval.Stop();
}
原因
you may have started the timer from another thread, so try invoking it from the correct thread.
参考
c# - Timer won't tick - Stack Overflow
WinForm Windows.Forms.Timer Start方法无效,Tick 无效,不执行_winform的 tick-CSDN博客
原文地址:https://blog.csdn.net/qq_35629563/article/details/145206619
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!