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

相关推荐
IM1GENIUS5 分钟前
.NET高频技术点(持续更新中)
c#·.net
serve the people9 分钟前
解决osx-arm64平台上conda默认源没有提供 python=3.7 的官方编译版本的问题
开发语言·python·conda
red-fly35 分钟前
c#修改ComboBox当前选中项的文本
c#·combobox
柒七爱吃麻辣烫36 分钟前
在Linux中安装JDK并且搭建Java环境
java·linux·开发语言
极小狐1 小时前
如何构建容器镜像并将其推送到极狐GitLab容器镜像库?
开发语言·数据库·机器学习·gitlab·ruby
多多*1 小时前
Java反射 八股版
java·开发语言·hive·python·sql·log4j·mybatis
正在走向自律1 小时前
从0到1:Python机器学习实战全攻略(8/10)
开发语言·python·机器学习
FY_20182 小时前
键盘输出希腊字符方法
开发语言
西西弗Sisyphus2 小时前
Python 处理图像并生成 JSONL 元数据文件 - 灵活text版本
开发语言·python
q567315232 小时前
Go语言多线程爬虫与代理IP反爬
开发语言·爬虫·tcp/ip·golang