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

相关推荐
大邳草民几秒前
Python 对象模型与属性访问机制
开发语言·笔记·python
xyq20244 分钟前
Swift 下标脚本
开发语言
计算机安禾7 分钟前
【数据结构与算法】第44篇:堆(Heap)的实现
c语言·开发语言·数据结构·c++·算法·排序算法·图论
chushiyunen17 分钟前
python fastapi使用、uvicorn
开发语言·python·fastapi
成都易yisdong20 分钟前
实现三北方向转换计算器(集成 WMM2025 地磁模型)
开发语言·windows·算法·c#·visual studio
白露与泡影25 分钟前
2026 全新 Java 面试题汇总(含答案)
java·开发语言
jinanwuhuaguo31 分钟前
OpenClaw 2026年4月升级大系深度解读剖析:从“架构重塑”到“信任内建”的范式跃迁
android·开发语言·人工智能·架构·kotlin·openclaw
geovindu42 分钟前
go: Simple Factory Pattern
开发语言·后端·设计模式·golang·简单工厂模式
xixixi777771 小时前
从5G标准到6G前沿:Polar码的技术演进与未来之路
开发语言·人工智能·5g·大模型·php·通信·polar码
小二李1 小时前
什么是依赖注入(DI)&控制反转IoC
java·开发语言