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博客

相关推荐
molong93137 分钟前
Kotlin 内联函数、高阶函数、扩展函数
android·开发语言·kotlin
盼哥PyAI实验室1 小时前
踏上编程征程,与 Python 共舞
开发语言·python
阿无,1 小时前
Java设计模式之工厂模式
java·开发语言·设计模式
weixin_307779131 小时前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json
ss2732 小时前
手写MyBatis第104弹:SqlSession从工厂构建到执行器选择的深度剖析
java·开发语言·后端·mybatis
周杰伦_Jay2 小时前
【Java集合体系】全面解析:架构、原理与实战选型
java·开发语言·数据结构·链表·架构
Camel卡蒙2 小时前
DDD架构——实体、聚合、值对象
java·开发语言·架构
hsjkdhs3 小时前
C++之多态
开发语言·jvm·c++
四维碎片3 小时前
【Qt】乌班图安装Qt环境
开发语言·数据库·qt
kyle~3 小时前
C++STL---静态数组array
开发语言·c++