COMポートへのハンドルを開き、そこにいくつかのバイトを書き込み、いくつかのバイトを読み取り、ハンドルを閉じて終了するCプログラムがあります。GetCommState
しかし、プログラムを10回続けて実行すると、関数を完了して関数でスタックするのに非常に長い時間がかかり始めSetCommState
ます。同じことが、単純なSerialPort
オブジェクトを使用するC#でも発生します。
私が見つけた唯一の修正は、デバイスをポートに再接続することです。このフリーズを取り除くためのよりエレガントな方法はありますか?たぶん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
すぐには戻らず(非同期で呼び出されますが)、約2分間ハングします。2番目の問題:2分後にエラーコード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.