我正在尝试识别接收特定字符串的串行端口(com)。无论如何,如果我在每个com上循环,则C#在某些端口上连接后锁定了读取线(例如com 10)。
我正在考虑在新的Thread
上启动SerialPort
.ReadLine()
,并且在持续一段时间后,我杀死了此线程。无论如何,我在想是否有一种更加"优雅"的方法来获得相同的结果。
此处发布了代码的一部分:
String com="";
for (int i= 0; i< ports.Length; i++) //ports is an array of String, the elements are the opened COM
{
mysp= new SerialPort(ports[i], 9600);
try {
mysp.Open();
String temp = mysp.ReadLine(); //HERE INFINITE LOOP ON CERTAIN PORTS
if (temp.IndexOf("*") > -1)
{
com = ports[i]; //Set the correct COM port
i = ports.Length;
mysp.Close();
}
}catch(Exception e)
{
Console.WriteLine("Exception "+e+" on " + ports[i]);
mysp.Close();
}
}
编辑:我纠正了问题,正如评论中的jdweng所建议。它不会在.Open()
上阻塞,但确实会阻止.ReadLine()
。
您可以用指定的超时将呼叫包装在Task
中。
int timeout = 5000; // Cancel the task after 5 seconds
Task.Run(() => {
var temp = mysp.ReadLine(); //HERE INFINITE LOOP ON CERTAIN PORTS
if (temp.IndexOf("*") > -1)
{
com = ports[i]; //Set the correct COM port
i = ports.Length;
mysp.Close();
}
}).Wait(timeout);
也应在例外后将mysp.Close();
移至finally
块中。
您可以让用户配置要使用的端口,这通常是这样做的。
或打开所有可用端口,等待您的连接,然后关闭未使用的端口。