如果端口接收没有串口c中的消息,则添加thread.sleep# [英] add thread.sleep if port receive did not message in Serial Port c#

查看:61
本文介绍了如果端口接收没有串口c中的消息,则添加thread.sleep#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码通过串口发送接收数据,如下所示:



 serialPort1.WriteLine(item); 
Thread.Sleep( 10000 );
sRecv = serialPort1.ReadExisting()。ToString();





发送数据然后在线程后接收数据.sleep 10秒,但是当10秒后Port没有收到数据的问题,如果没有收到数据,如果在接下来的10秒内如何添加Thread.sleep。

解决方案

不要。

如果你开始添加Thread.Sleep来等待RX数据,那么你的用户界面会变得没有响应,你的用户会认为你的应用已经崩溃了。特别是如果它冻结十秒钟!



相反,处理 SerialPort.DataReceived事件 [ ^ ]并使用Timer让用户知道没有收到任何内容。



如果您没有收到任何信息,那么您需要查看端口的配置方式,配置另一端设备的方式,并尝试首先通过HyperTerminal或类似方式获得响应。


错误的想法。你不应该这样做。相反,您可以使用将进入等待状态的单独线程,而无需调用 Thread.Sleep 。当您刚从端口读取数据并未准备好时,它将使您的线程处于等待状态。它不会浪费任何CPU时间,因为端口驱动程序可以通过硬件中断正常工作。当数据准备好读取时,您的线程将被唤醒,但还有其他原因可以唤醒:线程中止,超时等等。



-SA

ih have code send receive data through serial port like below :

serialPort1.WriteLine(item);
                Thread.Sleep(10000);
                sRecv = serialPort1.ReadExisting().ToString();



while sending the data and then receive the data after Thread.sleep 10 seconds, but the problem when Port did not receive the data after 10 seconds, how is it to add Thread.sleep if in the next 10 seconds if no data is received.

解决方案

Don't.
If you start adding Thread.Sleep to "wait" for RX data, then your UI becomes unresponsive, and your users assume your app has crashed. Particularly if it freezes for ten seconds!

Instead, handle the SerialPort.DataReceived event[^] and use a Timer to let the user know that nothing is being received.

If you aren't receiving anything, then you need to look at how your port is configured, how the device on the other end is configured, and try to get a response via HyperTerminal or similar first.


Wrong idea. You should not do it. Instead, you can use the separate thread which will go to the wait state without calling Thread.Sleep. When you just read from the port, and the data is not ready, it will put your thread in a wait state. It won't waste any CPU time, because the port driver works properly by hardware interrupt. Your thread will be waken up when data is ready for reading, but there are other reasons for waking up: thread abort, timeout, and so on.

—SA


这篇关于如果端口接收没有串口c中的消息,则添加thread.sleep#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆