C#,杀死一段时间后尝试连接的串口

时间:2016-11-29 14:15:39

标签: c# serial-port

我正在尝试识别接收某个字符串的串行端口(COM)。 无论如何,如果我在每个COM上循环,C#会在某些端口(例如COM 10)上连接后锁定ReadLine。

我正在考虑在新的SerialPort上启动.ReadLine() Thread,经过一段时间后我就杀了这个帖子。 无论如何,我在想是否有更多的优雅"实现相同结果的方法。

以下是代码的一部分:

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()

2 个答案:

答案 0 :(得分:0)

您可以让用户配置要使用的端口,通常是这样做的。

或者打开所有可用端口,等待连接,然后关闭未使用的端口。

答案 1 :(得分:0)

您可以将呼叫包裹在具有指定超时的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块。

相关问题