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

相关推荐
我居然是兔子5 小时前
异常练习:在试错中吃透Java异常处理的底层逻辑
java·开发语言
钰fly6 小时前
C#异常处理 递归算法
c#
养一回月亮!6 小时前
使用Qt实现简单绘图板:鼠标绘制与擦除功能详解
开发语言·qt
BanyeBirth6 小时前
C++差分数组(二维)
开发语言·c++·算法
ejjdhdjdjdjdjjsl6 小时前
JSON序列化与反序列化实战指南
数据库·microsoft·c#
Tony Bai6 小时前
Go 的 AI 时代宣言:我们如何用“老”原则,解决“新”问题?
开发语言·人工智能·后端·golang
Fcy6486 小时前
C++ map和multimap的使用
开发语言·c++·stl
L Jiawen7 小时前
【Golang基础】基础知识(下)
服务器·开发语言·golang
云栖梦泽8 小时前
鸿蒙应用AI赋能与国际化落地实战:让待办应用跨越语言与智能边界
开发语言·鸿蒙系统
CoderCodingNo8 小时前
【GESP】C++五级真题(结构体排序考点) luogu-B3968 [GESP202403 五级] 成绩排序
开发语言·c++·算法