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

相关推荐
czxyvX6 分钟前
010-C++11
开发语言·c++
亓才孓33 分钟前
【MyBatis Plus】Wrapper接口
java·开发语言·数据库·spring boot·mybatis
游乐码1 小时前
c#运算符重载
开发语言·c#
人道领域1 小时前
MyBatisPlus高效开发实战指南
java·开发语言·数据库
游乐码1 小时前
c#继承的原则
开发语言·c#
lsx2024061 小时前
Servlet 文件上传
开发语言
游乐码1 小时前
c#内部类和分部类
开发语言·c#
消失的旧时光-19431 小时前
C++ 多线程与并发系统取向(四)—— std::condition_variable:线程协作与生产者消费者模型(类比 Java wait/notify)
开发语言·c++
csbysj20202 小时前
Java Override/Overload
开发语言
globaldomain2 小时前
立海世纪:优质品牌域名对企业的潜在价值
开发语言·php·主机·网站·域名注册