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

相关推荐
十八朵郁金香22 分钟前
通俗易懂的DOM1级标准介绍
开发语言·前端·javascript
阿尔法波25 分钟前
python与pycharm如何设置文件夹为源代码根目录
开发语言·python·pycharm
xing251634 分钟前
pytest下allure
开发语言·python·pytest
眸笑丶38 分钟前
使用 Python 调用 Ollama API 并调用 deepseek-r1:8b 模型
开发语言·python
enyp801 小时前
Qt QStackedWidget 总结
开发语言·qt
gu201 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
lly2024061 小时前
SQLite 删除表
开发语言
wjs20241 小时前
HTML 字符实体
开发语言
二十雨辰1 小时前
[Java基础]网络编程
java·开发语言
AC使者2 小时前
介绍 TensorFlow 的基本概念和使用场景。
开发语言·自然语言处理·sqlite·github