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

相关推荐
2501_944521596 分钟前
Flutter for OpenHarmony 微动漫App实战:列表项组件实现
android·开发语言·javascript·flutter·ecmascript
【赫兹威客】浩哥7 分钟前
【赫兹威客】Redis安装与验证教程
开发语言·php
froginwe117 分钟前
SVG 简介
开发语言
宵时待雨9 分钟前
数据结构(初阶)笔记归纳7:链表OJ
c语言·开发语言·数据结构·笔记·算法·链表
无心水13 分钟前
8、吃透Go语言container包:链表(List)与环(Ring)的核心原理+避坑指南
java·开发语言·链表·微服务·架构·golang·list
froginwe1119 分钟前
Python3 集合
开发语言
人工智能AI技术21 分钟前
【C#程序员入门AI】环境一键搭建:.NET 8+AI开发环境(Semantic Kernel/ML.NET/ONNX Runtime)配置
人工智能·c#
lly20240624 分钟前
R 绘图 - 条形图
开发语言
无心水28 分钟前
6、Go语言类型判断与转换避坑指南:从类型断言到别名类型全解析
开发语言·后端·golang
a程序小傲32 分钟前
SpringBoot 秒实现在线 Word 编辑、协同、转化等功能
java·开发语言·spring boot·后端·spring·word·深度优先