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

相关推荐
矶鹬笛手14 小时前
(2.1) 信息技术及其发展
sql·计算机网络·c#
u***276115 小时前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
p***h64315 小时前
JavaScript在Node.js中的异步编程
开发语言·javascript·node.js
散峰而望15 小时前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github
Porunarufu15 小时前
Java·关于List
java·开发语言
子不语18015 小时前
Python——函数
开发语言·python
ndjnddjxn16 小时前
Rust学习
开发语言·学习·rust
月光技术杂谈16 小时前
实战:C驱动框架嵌入Rust模块的互操作机制与完整流程
c语言·开发语言·rust·ffi·跨语言·bindgen·互操作
t1987512816 小时前
基于MATLAB的指纹识别系统完整实现
开发语言·matlab
笑非不退16 小时前
C# c++ 实现程序开机自启动
开发语言·c++·c#