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

相关推荐
shx66661 分钟前
2.2.1 ROS2 在功能包中编写 Python 节点
开发语言·python·ros2
逆小舟3 分钟前
【matlab】simulink实践经验(12.3)
开发语言·matlab
小汪学不会9 分钟前
(自用)mmcv下载失败
开发语言
切糕师学AI9 分钟前
.NET 如何引用两个不同版本的dll?
c#·.net
水木姚姚13 分钟前
C++ begin
开发语言·c++·算法
洛_尘23 分钟前
JAVA第十一学:认识异常
java·开发语言
毕设源码-邱学长41 分钟前
【开题答辩全过程】以 基于JavaScript的图书销售网站为例,包含答辩的问题和答案
开发语言·javascript·ecmascript
老王熬夜敲代码1 小时前
泛型编程的差异抽象思想
开发语言·c++·笔记
zqy02271 小时前
python安装与环境配置
开发语言·python