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

相关推荐
云知谷4 分钟前
【经典书籍】《代码整洁之道》第六章“对象与数据结构”精华讲解
c语言·开发语言·c++·软件工程·团队开发
dragoooon3412 分钟前
[Linux——Lesson23.线程概念与控制:线程基础]
java·开发语言·jvm
xixixi7777723 分钟前
攻击链重构的具体实现思路和分析报告
开发语言·python·安全·工具·攻击链
想拿大厂offer31 分钟前
Windows Server 2022 + IIS + .NET 8 + MySQL 部署手册
c#·asp.net
蓝桉~MLGT39 分钟前
Python学习历程——模块
开发语言·python·学习
庙堂龙吟奈我何1 小时前
js中哪些数据在栈上,哪些数据在堆上?
开发语言·javascript·ecmascript
武子康1 小时前
Java-169 Neo4j CQL 实战速查:字符串/聚合/关系与多跳查询
java·开发语言·数据库·python·sql·nosql·neo4j
一只小灿灿1 小时前
深入解析 Maven 与 Gradle:Java 项目构建工具的安装、使用
java·开发语言·maven
树在风中摇曳1 小时前
C语言 | 文件操作详解与实战示例
c语言·开发语言