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

相关推荐
郑同学的笔记28 分钟前
【Qt教程29】Qt5和Qt6版本对比
开发语言·qt
基德爆肝c语言32 分钟前
Qt 主窗口全家桶:菜单栏、工具栏、状态栏与对话框完全指南
开发语言·qt
XMYX-02 小时前
28 - Go JSON 数据操作
开发语言·golang·json
三*一2 小时前
Mapbox GL JS 自研面要素整形工具开发实录
开发语言·javascript·arcgis·ecmascript
超级小星星2 小时前
C 语言结构体内存对齐深度解析:从概念到实战
c语言·开发语言
狮子座明仔3 小时前
AgentSPEX:当 Agent 框架开始把“控制流“从 Python 里抠出来
开发语言·python
qq_431280703 小时前
上位与基恩士PLC通讯工作记录
c#
笨笨饿3 小时前
74_SysTick滴答定时器中断
c语言·开发语言·人工智能·单片机·嵌入式硬件·算法·学习方法
科芯创展3 小时前
XZ4058B/C,20V,外置MOS,8.4V/8.7V开关充电芯片 宽范围电源电压:8.9V~20V-(电池充电电压:8.4V/8.7V)
c语言·开发语言
AI玫瑰助手3 小时前
Python流程控制:break与continue语句的区别与应用
开发语言·python·信息可视化