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

相关推荐
你不是我我1 天前
【Java 开发日记】HTTP3 性能更好,为什么内网微服务依然多用 HTTP2?HTTP2 内网优势是什么?
java·开发语言·微服务
tjl521314_211 天前
04C++ 名称空间(Namespace)
开发语言·c++
赏金术士1 天前
Kotlin 数据流与单双向绑定
android·开发语言·kotlin
逻辑驱动的ken1 天前
Java高频面试场景题25
java·开发语言·深度学习·面试·职场和发展
AI人工智能+电脑小能手1 天前
【大白话说Java面试题】【Java基础篇】第32题:Java的异常处理机制是什么
java·开发语言·后端·面试
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ1 天前
通过java后端代码来实现给word内容补充格式文本内容控件,以及 设置控件的标记和标题
java·c#·word
無限進步D1 天前
Java 面向对象高级 接口
java·开发语言
两年半的个人练习生^_^1 天前
Java日志框架和使用、日志记录规范
java·开发语言·开发规范
杨凯凡1 天前
【032】排查入门:jstack、heap dump、Arthas 初识
java·开发语言·后端
其实防守也摸鱼1 天前
无线网络安全--实验 规避WLAN验证之发现隐藏的SSID
java·开发语言·网络·安全·web安全·智能路由器·无线网络安全