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

相关推荐
Touper.22 分钟前
JavaSE -- 泛型详细介绍
java·开发语言·算法
sun00770024 分钟前
std::forward作用
开发语言·c++·算法
一名用户1 小时前
unity实现梦日记式传送组件
后端·c#·unity3d
Zhen (Evan) Wang1 小时前
(豆包)xgb.XGBRegressor 如何进行参数调优
开发语言·python
虾球xz1 小时前
CppCon 2018 学习:THE MOST VALUABLE VALUES
开发语言·c++·学习
阿蒙Amon2 小时前
C#扩展方法全解析:给现有类型插上翅膀的魔法
开发语言·c#
尘浮7282 小时前
60天python训练计划----day59
开发语言·python
Chef_Chen3 小时前
从0开始学习R语言--Day39--Spearman 秩相关
开发语言·学习·r语言
不学会Ⅳ3 小时前
Mac M芯片搭建jdk源码环境(jdk24)
java·开发语言·macos
好开心啊没烦恼4 小时前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas