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

相关推荐
2401_8919573110 分钟前
list的一些特性(C++)
开发语言·c++
二十雨辰20 分钟前
[尚庭公寓]07-Knife快速入门
java·开发语言·spring
Python大数据分析@21 分钟前
Origin、MATLAB、Python 用于科研作图,哪个最好?
开发语言·python·matlab
编程零零七1 小时前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
我爱Jack1 小时前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
米饭「」1 小时前
C++AVL树
java·开发语言·c++
心愿许得无限大2 小时前
Qt 常用界面组件
开发语言·c++·qt
2401_858286112 小时前
OS15.【Linux】gdb调试器的简单使用
linux·运维·服务器·开发语言·gdb
牛马baby2 小时前
MATLAB下载安装教程(附安装包)2025最新版(MATLAB R2024b)
开发语言·matlab
shenyan~2 小时前
关于 c、c#、c++ 三者区别
开发语言·c++