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

相关推荐
foundbug999几秒前
利用MATLAB计算梁单元刚度矩阵并组装成总体刚度矩阵
开发语言·matlab·矩阵
码农水水2 分钟前
小红书Java面试被问:mTLS(双向TLS)的证书验证和握手过程
java·开发语言·数据库·redis·python·面试·开源
zmzb01033 分钟前
C++课后习题训练记录Day85
开发语言·c++·算法
梵刹古音3 分钟前
【C语言】 整型变量
c语言·开发语言
工程师老罗3 分钟前
Python中__call__和__init__的区别
开发语言·pytorch·python
JSON_L5 分钟前
PHP项目打包为桌面应用
开发语言·php·桌面应用
2301_822366356 分钟前
C++中的协程编程
开发语言·c++·算法
m0_736919106 分钟前
C++中的事件驱动编程
开发语言·c++·算法
上海合宙LuatOS8 分钟前
LuatOS框架的使用(1)
java·开发语言·单片机·嵌入式硬件·物联网·ios·iphone
lxl130714 分钟前
学习C++(4)构造函数+析构函数+拷贝构造函数
开发语言·c++·学习