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

相关推荐
lsx2024063 小时前
Bootstrap 按钮
开发语言
神仙别闹3 小时前
基于 Python 实现 BERT 的情感分析模型
开发语言·python·bert
禾叙_3 小时前
【langchain4j】结构化输出(六)
java·开发语言
NQBJT3 小时前
VS Code配置Python人工智能开发环境
开发语言·人工智能·vscode·python
byoass3 小时前
智巢AI知识库深度解析:企业文档管理从大海捞针到精准狙击的进化之路
开发语言·网络·人工智能·安全·c#·云计算
南境十里·墨染春水4 小时前
C++笔记 STL——set
开发语言·c++·笔记
L1624764 小时前
Win11 共享→Windows Server 访问故障总结(极简可复用)
开发语言·windows·php
.柒宇.4 小时前
FastAPI 基础指南:从入门到实战
开发语言·python·fastapi
xyq20244 小时前
Go 错误处理
开发语言
JAVA面经实录9175 小时前
企业级java+LangChain4j-RAG系统 限流熔断降级
java·开发语言·分布式·langchain