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

相关推荐
Zz_waiting.8 分钟前
统一服务入口-Gateway
java·开发语言·gateway
四维碎片28 分钟前
【Qt】大数据量表格刷新优化--只刷新可见区域
开发语言·qt
时光追逐者29 分钟前
【拾遗补漏】.NET 常见术语集
微软·c#·.net
薛慕昭37 分钟前
C语言核心技术深度解析:从内存管理到算法实现
c语言·开发语言·算法
火星数据-Tina1 小时前
Python + WebSocket 实现实时体育比分系统(含数据库设计与前端演示)
开发语言·前端
秋雨雁南飞1 小时前
c# 使用Memory实现Redis入队出队功能
redis·c#
⑩-1 小时前
浅学Java-设计模式
java·开发语言·设计模式
攻心的子乐1 小时前
软考 关于23种设计模式
java·开发语言·设计模式
qq_479875432 小时前
C++ ODR
java·开发语言·c++
一叶之秋14122 小时前
Qt开发初识
开发语言·qt