C# 正在为数组分配动态数量的值,从而导致异常。我如何绕过这个?

C# 正在为数组分配动态数量的值,从而导致异常。我如何绕过这个?,c#,arrays,exception,try-catch,C#,Arrays,Exception,Try Catch,所以基本上我要么有一个无限循环(没有try-catch),要么有一个异常停止代码。我错过了什么明显的东西吗?在此之后,我需要执行更多代码。我不知道串行端口,但根据您提供的代码: try { while (true) //cant verify against port.readline == null directly { output = Convert.ToString(port.ReadLine()); //causes exception

所以基本上我要么有一个无限循环(没有try-catch),要么有一个异常停止代码。我错过了什么明显的东西吗?在此之后,我需要执行更多代码。

我不知道串行端口,但根据您提供的代码:

try
{
    while (true) //cant verify against port.readline == null directly
    {
        output = Convert.ToString(port.ReadLine()); //causes exception
        lines++;

        if (lines > 5)
        {
            holder = output.Split(delimiters);
        }
    }
}
catch (Exception) { }


MessageBox.Show("Unreachable!");

使用
break
语句将把您踢出无限循环。

啊,对不起,这是一个串行端口,
port=new SerialPort(“COM6”,19200,奇偶校验。无,8,停止位。1)
为什么不在while循环中移动try/catch?问题是
ReadLine
是一种阻塞方法,在读取换行符或抛出TimeoutException(如果设置了
ReadTimeout
)之前不会返回。这意味着操作的结果永远不应该为空;相反,正确的方法是分别捕获和处理TimeoutException,并相应地调整超时值(默认情况下应为500ms)。编辑:
var portValue = port.ReadLine();
if (portValue == null)
    break; // *** This is the magic you're looking for ***

output = Convert.ToString(portValue);