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

相关推荐
于慨3 分钟前
flutter基础组件用法
开发语言·javascript·flutter
历程里程碑4 分钟前
二叉树---翻转二叉树
开发语言·c++·elasticsearch·链表·搜索引擎·tornado·dash
Rsun0455128 分钟前
16、Java 迭代器模式从入门到实战
java·开发语言·迭代器模式
We་ct32 分钟前
Git 核心知识点全解析
开发语言·前端·git·gitee·github
iDao技术魔方36 分钟前
Bun v1.3.12 深度解析:新特性、性能优化与实战指南
开发语言·javascript·visual studio code
charlie1145141911 小时前
嵌入式C++工程实践——第13篇:第一次重构 —— enum class取代宏,类型安全的开始
开发语言·c++·vscode·stm32·安全·重构·现代c++
jiayong231 小时前
第 13 课:分页、页码状态和 URL 同步
开发语言·前端·javascript·vue.js·学习
CHANG_THE_WORLD1 小时前
C++ 文件读取函数完全指南
开发语言·c++
阿正的梦工坊1 小时前
JavaScript 闭包 × C++ 类比:彻底搞懂闭包
开发语言·javascript·c++
赵优秀一一1 小时前
SQLAlchemy学习记录
开发语言·数据库·python