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

相关推荐
爱写代码的小朋友4 分钟前
使用 Nuitka 打包 Python 应用:从入门到进阶
开发语言·python
yuan199979 分钟前
C# 断点续传下载文件工具设计与实现
开发语言·c#
想唱rap10 分钟前
线程之条件变量和生产消费模型
java·服务器·开发语言·数据库·mysql·ubuntu
Boop_wu26 分钟前
[Java 算法] 栈
java·开发语言·算法
来自远方的老作者27 分钟前
第7章 运算符-7.5 比较运算符
开发语言·数据结构·python·算法·代码规范·比较运算符
南境十里·墨染春水28 分钟前
C++笔记 Lambda表达式
开发语言·c++·笔记
We་ct32 分钟前
LeetCode 201. 数字范围按位与:位运算高效解题指南
开发语言·前端·javascript·算法·leetcode·typescript
程序员榴莲33 分钟前
Java(十二)抽象类
java·开发语言
木子欢儿39 分钟前
在 Fedora 上配置 Go 语言(Golang)开发环境
开发语言·后端·golang
超级大只老咪1 小时前
线性递推通用模板
java·开发语言·算法