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

相关推荐
头发还没掉光光5 分钟前
Linux网络之TCP协议
linux·运维·开发语言·网络·网络协议·tcp/ip
讳疾忌医丶14 分钟前
C++中虚函数调用慢5倍?深入理解vtable和性能开销
开发语言·c++
宵时待雨14 分钟前
数据结构(初阶)笔记归纳5:单链表的应用
c语言·开发语言·数据结构·笔记·算法
JaredYe15 分钟前
node-plantuml-2:革命性的纯Node.js PlantUML渲染器,告别Java依赖!
java·开发语言·node.js·uml·plantuml·jre
派大鑫wink19 分钟前
【Day38】Spring 框架入门:IOC 容器与 DI 依赖注入
java·开发语言·html
rit843249919 分钟前
基于偏振物理模型的水下图像去雾MATLAB实现
开发语言·matlab
kklovecode20 分钟前
数据结构---顺序表
c语言·开发语言·数据结构·c++·算法
孩子 你要相信光23 分钟前
解决:React 中 map 处理异步数据不渲染的问题
开发语言·前端·javascript
jllllyuz24 分钟前
ANPC三电平逆变器损耗计算的MATLAB实现
开发语言·matlab·php
aini_lovee25 分钟前
基于MATLAB Simulink的定轴齿轮与行星齿轮仿真模型
开发语言·matlab