"Index out of range exception" 当索引不超出范围时

"Index out of range exception" when index is not out of range

下面显示的函数在随机抛出索引超出范围异常之前执行了很多次:

public void AddDataT()
        {
            timeT = SerialPortClass.GetInstance().GetTime();
            if (DateTime.Compare(timeT[0], tempTimeT[499]) < 0)
                return;

            foreach (Series ptSeries in chartT.Series)
            {
                if (ptSeries.Name == "Temperature 1")
                    data = SerialPortClass.GetInstance().GetBuffer(5);
                else if (ptSeries.Name == "Temperature 2")
                    data = SerialPortClass.GetInstance().GetBuffer(6);
                else return;

                indexT = 0;
                foreach (float value in data.Latest())
                {
                    AddNewPoint("Temperature", timeT[indexT], value, ptSeries);
                    tempTimeT[indexT] = timeT[indexT];
                    indexT++;
                }
            }
        }

如屏幕截图所示,异常时刻的索引为 499,数组大小为 500。我知道我正在根据其大小遍历另一个缓冲区,但是数据和时间缓冲区总是有 500 个元素。知道什么可能导致异常吗?这是 AddNewPoint 函数的代码:

        public void AddNewPoint(String chart, DateTime timestamp, float point,
            System.Windows.Forms.DataVisualization.Charting.Series ptSeries)
        {
            if (chart == "Voltage")
                scale = scaleV;
            else if (chart == "Current")
                scale = scaleI;
            else scale = scaleT;
            
            ptSeries.Points.AddXY(timestamp, point);
            double removeBefore = timestamp.AddSeconds((double)(scale) * (-1)).ToOADate();

            while (ptSeries.Points[0].XValue < removeBefore)
            {
                ptSeries.Points.RemoveAt(0);
            }

            if (chart == "Voltage")
            {
                chartV.ChartAreas[0].AxisX.Minimum = ptSeries.Points[0].XValue;
                chartV.ChartAreas[0].AxisX.Maximum = DateTime.FromOADate(ptSeries.Points[0].XValue).AddSeconds(scale).ToOADate();
                chartV.Invalidate();
            }
            else if (chart == "Current")
            {
                chartI.ChartAreas[0].AxisX.Minimum = ptSeries.Points[0].XValue;
                chartI.ChartAreas[0].AxisX.Maximum = DateTime.FromOADate(ptSeries.Points[0].XValue).AddSeconds(scale).ToOADate();
                chartI.Invalidate();
            }
            else
            {
                chartT.ChartAreas[0].AxisX.Minimum = ptSeries.Points[0].XValue;
                chartT.ChartAreas[0].AxisX.Maximum = DateTime.FromOADate(ptSeries.Points[0].XValue).AddSeconds(scale).ToOADate();
                chartT.Invalidate();
            }
        }

这种情况不会一直发生,所以我正在考虑只使用一个 try 语句,这样程序可以在偶尔发生这种异常时保持 运行。

在第 210 行放置一个条件断点。

设置条件为indexT >= 499

现在调试您的代码,如果您不确定如何调试请观看一些视频,学习最方便的功能需要 10-15 分钟。