应用程序被终止后.Net SerialPort 仍然锁定

发布于 2024-09-24 09:32:53 字数 393 浏览 4 评论 0原文

我有一个调用 SerialPort.Open() 的应用程序... 这工作正常,数据是通过端口读取/写入的。 但是,如果用户决定通过 TaskManager 终止应用程序,应用程序将关闭,而不会调用我的析构函数(调用 SerialPort.Close())。

这反过来(仅有时)会导致以下错误:

对端口“COM2”的访问被拒绝。

重新启动应用程序时会发生这种情况。 我已经阅读了足够多的帖子,知道如果正确调用 .Close() 就不会发生这种情况。 到目前为止,我已经通过一个计时器来处理这个问题,它重新尝试 .Open().. 最终成功(我认为它在大多数情况下都会成功)。

我的问题是:

是否有 DLLImport 方法可以让我释放 Comm 端口资源?

I have an application which calls SerialPort.Open() ...
This works fine and data is read/written through the port.
However if a user decides to kill the Application through the TaskManager the application will close without calling my destructor calling SerialPort.Close().

This in turn (only sometimes) causes the following error:

Access to the port 'COM2' is denied.

This occurs on re-startup of the application.
I've read enough posts to know that this wouldn't happen if .Close() was properly called.
So far I have handled this by having a timer which reattempts the .Open().. which eventually succeeds (that is I think it does most of the time).

My question is this:

Is there a DLLImport method which will allow me to free the Comm port resource?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

手心的海 2024-10-01 09:32:53

我擦了擦我的水晶球,发现你正在使用一个模拟串行端口的 USB 驱动程序,用户认为终止该进程是个好主意,因为她将 USB 连接器从插座中猛拉出来,并且她正在运行一个Vista 之前的 Windows 版本。

大约是该列表中的任意两种组合。是的,不起作用,当进程有一个内核线程正在完成无法完成的 I/O 请求时,您无法终止该进程。当您使用“查看+选择列”并勾选“句柄”时,您可以从 TaskMgr.exe 中得知。当一个句柄打开时,该进程将成为僵尸进程。在司机真正放手之前不会关闭。不会发生的,USB 驱动程序太糟糕了。

再次启动程序会爆炸,进程的第一个实例仍然打开端口。拒绝访问。

告诉用户不要将手放在连接器上。或者从不同的制造商处购买另一件。您可以通过向程序中添加“安全删除硬件”菜单选项来提供帮助。这会调用 SerialPort.Close() 方法。调用 Sleep(2500) 并显示一个消息框,表明可以拔掉插头。

I rubbed my crystal ball and it revealed that you are using a USB driver that emulates a serial port, that the user decided it was a good idea to kill the process because she jerked the USB connector out of the socket and that she is running a pre-Vista version of Windows.

Roughly any two combinations out of that list. Yes, doesn't work, you cannot kill a process when it has a kernel thread going that is completing an I/O request that cannot finish. You can tell from TaskMgr.exe when you use View + Select Columns and tick Handles. The process will zombie with one handle opened. Won't close until the driver actually lets go. Won't happen, USB drivers suck like that.

Starting the program again will bomb, the first instance of the process still has the port opened. Access denied.

Tell the user to keep her hands off the connector. Or buy another one from a different manufacturer. You can help by adding a "Safely Remove Hardware" menu option to your program. That calls the SerialPort.Close() method. Call Sleep(2500) and display a message box that it is okay to unplug it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文