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

相关推荐
SunnyDays10112 分钟前
如何使用 C# 将 PDF 转换为 SVG:完整指南
c#·pdf转svg
nbsaas-boot6 分钟前
Go 语言中的集合体系:从语言设计到工程实践
开发语言·后端·golang
李日灐7 分钟前
C++STL:deque、priority_queue详解!!:详解原理和底层
开发语言·数据结构·c++·后端·stl
阿坤带你走近大数据7 分钟前
JavaScript脚本语言的简单介绍
开发语言·javascript·ecmascript
yangminlei7 分钟前
Spring Boot 实现 DOCX 转 PDF
开发语言·spring boot·python
悟道|养家8 分钟前
基于L1/L2 缓存访问速度的角度思考数组和链表的数据结构设计以及工程实践方案选择(2)
java·开发语言·缓存
wjs20248 分钟前
堆的基本存储
开发语言
虫小宝10 分钟前
微信群发消息API接口对接中Java后端的请求参数校验与异常反馈优化技巧
android·java·开发语言
Main. 2412 分钟前
从0到1学习Qt -- Qt3D入门
开发语言·qt·学习
接着奏乐接着舞。13 分钟前
Go 一小时上手指南:从零到运行第一个程序
开发语言·后端·golang