gpt4 book ai didi

c# - 为什么在 SerialPort.Open 和 Close 之前使用 Thread.Sleep()?

转载 作者:太空狗 更新时间:2023-10-29 20:59:39 29 4
gpt4 key购买 nike

我注意到我在 SerialPort 关闭和打开时阅读的示例代码,人们会在 SerialPort.Open() 和 Close() 之前添加 Thread.Sleep(1000)。像下面这样:

Thread.Sleep(1000);
serialPort1.Open();
/* some code */
Thread.Sleep(1000);
serialPort1.Close();

我在任何地方都找不到任何解释。为什么人们在打开或关闭之前使用 Thread.Sleep 阻止串行端口?是出于某种计时目的吗?我是否也应该在读取或写入串行端口时放置一个 Thread.Sleep?

最佳答案

当您打开一个端口时,SerialPort 类会在后台启动一个新线程,该线程负责(通过 WaitCommEvent Windows API 函数)等待串行端口事件(例如数据到达)并向您的处理程序触发适当的事件.这就是为什么像 DataReceived 这样的事件实际上发生在辅助线程上的原因。

当您关闭端口时,Close() 调用会立即返回,但辅助线程需要一些时间才能停止。

如果您在调用 Close 后尝试过快地重新打开端口,并且线程尚未停止运转,则 SerialPort 实例未处于可以开始新连接的状态。

注意 MSDN documentation for SerialPort.Close状态:

The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.

您可以跟踪关闭端口的时间,并在再次打开它之前确保某个任意超时已经过去。

读/写之前不需要 sleep ,但要记住一些怪癖:

请记住,.NET BCL 中的 SerialPort 类仍然依赖于底层的 Win32 API,而且我认为自最初实现以来,它并没有得到 Microsoft 的大力支持。

有关详细信息,请参阅:

关于c# - 为什么在 SerialPort.Open 和 Close 之前使用 Thread.Sleep()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6434297/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com