我有一个 C 程序,它打开一个 COM 端口的句柄,向它写入一些字节,读取一些字节,然后关闭句柄并退出。但是,当我连续运行该程序 10 次时,开始需要很长时间才能完成该GetCommState
功能并卡在该SetCommState
功能中。同样的事情发生在 C# 的一个简单SerialPort
对象中。
我能找到的唯一解决方法是将设备重新连接到端口。有没有更优雅的方法来摆脱这种冻结?可能只是一些PC配置错误?
更新
我已经重写了代码以使其使用DeviceIoControl
而不是SetCommState
. 但是,这里的问题完全相同。
device =
CreateFileW(
L"\\\\.\\COM3", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, NULL);
static int SetBaudRate (HANDLE device) {
int error = 0;
int success = 0;
OVERLAPPED overlapped = {0};
overlapped.hEvent = CreateEvent(NULL, TRUE, 0, NULL);
if (overlapped.hEvent) {
SERIAL_BAUD_RATE baudRate = {0};
baudRate.BaudRate = SERIAL_BAUD_115200;
error =
DeviceIoControl(
device, IOCTL_SERIAL_SET_BAUD_RATE, &baudRate,
sizeof(SERIAL_BAUD_RATE), NULL, 0, NULL, &overlapped);
if (error || (!error && GetLastError() == ERROR_IO_PENDING)) {
DWORD bytes = 0;
if (GetOverlappedResult(device, &overlapped, &bytes, TRUE)) {
success = 1;
}
}
}
CloseHandle(overlapped.hEvent);
return success;
}
第一个问题:DeviceIoControl
不会立即返回(虽然是异步调用的)并且会挂起大约两分钟。第二个问题:在这两分钟之后,它失败并出现错误代码 121(ERR_SEM_TIMEOUT:“信号量超时期限已过期。”)。
- 使用的驱动是标准的windows驱动
usbser.sys
- 关于为什么函数调用没有立即返回的任何想法?如果没有,如何为函数设置更短的超时时间?
- 关于为什么功能失败的任何想法?
更新 2
也会冻结的示例 C# 代码(如上面的 C 程序):
using System;
using System.IO.Ports;
sealed class Program {
static void Main (string[] args) {
int i = 0;
while (true) {
Console.WriteLine(++i);
SerialPort p =
new SerialPort("com3", 115200, Parity.None, 8, StopBits.One);
p.DtrEnable = true;
p.RtsEnable = true;
p.ParityReplace = 0;
p.WriteTimeout = 10000;
p.ReadTimeout = 3000;
try {
p.Open();
Console.WriteLine("Success!");
} catch (Exception e) {
Console.WriteLine(e.GetType().Name + ": " + e.Message);
}
p.Close();
Console.ReadLine();
}
}
}
示例输出如下:
1 (device not yet connected)
IOException: The port 'com3' does not exist.
2 (device connected but not yet in windows device manager)
IOException: The port 'com3' does not exist.
3
IOException: The port 'com3' does not exist.
4 (device connected and recognized)
Success!
5
Success!
[...] (with about one second between each enter press)
15
Success!
16 (device still connected and recognized - nothing touched! after two minutes of freeze, semaphore timeout exactly as in the C version)
IOException: The semaphore timeout period has expired.
17 (device disconnected during the two minutes of freeze. it then returns instantly)
IOException: A device attached to the system is not functioning.
18 (device still disconnected - note that the exception is a different one than the one in the beginning although it's the same case: device not connected)
IOException: The specified port does not exist.
19
IOException: The port 'com3' does not exist.