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

相关推荐
CoderCodingNo4 分钟前
【GESP】C++八级考试大纲知识点梳理 (7) 算法的时间和空间效率分析
开发语言·c++·算法
程序员zgh4 分钟前
C++ 环形队列 从原理到实例演示
c语言·开发语言·数据结构·c++·学习
csbysj20204 分钟前
Bootstrap 下拉菜单:全面解析与应用指南
开发语言
sycmancia21 分钟前
Qt——窗口部件及窗口类型、坐标系统
开发语言·qt
南境十里·墨染春水22 分钟前
C++ 笔记 运算符重载(面象对象)
开发语言·c++·笔记
RDCJM23 分钟前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
小陈工23 分钟前
Python Web开发入门(一):虚拟环境与依赖管理,从零搭建纯净开发环境
开发语言·前端·数据库·git·python·docker·开源
运维行者_26 分钟前
金融和电商行业如何使用网络监控保障业务稳定?
开发语言·网络·人工智能·安全·web安全·机器学习·运维开发
csbysj202029 分钟前
Eclipse 视图(View)详解
开发语言
zhangzeyuaaa38 分钟前
# Python 抽象类(Abstract Class)
开发语言·python