C#中无法在串口serialPort1_DataReceived启动定时器的解决方法

这里的串口名是serialPort1,定时器名是timerRxInterval

方法1------修改启动方法

cs 复制代码
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------更改计时器的类型

删除显示界面的定时器

cs 复制代码
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博客

相关推荐
kkai人工智能7 小时前
AI写作:从“废话”到“爆款”
开发语言·人工智能·ai·ai写作
lizz3111 小时前
C++模板编程:从入门到精通
java·开发语言·c++
shoubepatien11 小时前
JAVA -- 05
java·开发语言
寰天柚子11 小时前
Java并发编程中的线程安全问题与解决方案全解析
java·开发语言·python
沐知全栈开发12 小时前
Bootstrap 下拉菜单:设计与实现指南
开发语言
Evand J12 小时前
【MATLAB例程】多锚点RSSI定位和基站选择方法,基于GDOP、基站距离等因素。以Wi-Fi定位为例,附下载链接
开发语言·matlab·定位·gdop·rssi
superman超哥12 小时前
仓颉语言中锁的实现机制深度剖析与并发实践
c语言·开发语言·c++·python·仓颉
JAVA+C语言12 小时前
String Constant Pool
java·开发语言
郝学胜-神的一滴12 小时前
OpenGL的glDrawElements函数详解
开发语言·c++·程序人生·游戏·图形渲染
moxiaoran575312 小时前
Go语言结构体
开发语言·后端·golang