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

相关推荐
json{shen:"jing"}几秒前
js收官总概述
开发语言·python
froginwe113 分钟前
Java 文档注释
开发语言
Zsy_0510034 分钟前
【C++】stack、queue、容器适配器
开发语言·c++
一起努力啊~5 分钟前
算法刷题--栈和队列
开发语言·算法
万行6 分钟前
SQL进阶&索引篇
开发语言·数据库·人工智能·sql
打工的小王8 分钟前
java并发编程(六)CountDownLatch和回环屏障CyclicBarrier
java·开发语言
星火开发设计11 分钟前
命名空间 namespace:解决命名冲突的利器
c语言·开发语言·c++·学习·算法·知识
小北方城市网11 分钟前
RabbitMQ 生产级实战:可靠性投递、高并发优化与问题排查
开发语言·分布式·python·缓存·性能优化·rabbitmq·ruby
爱学习的阿磊17 分钟前
C++中的策略模式应用
开发语言·c++·算法
郝学胜-神的一滴18 分钟前
Python中的bisect模块:优雅处理有序序列的艺术
开发语言·数据结构·python·程序人生·算法