The function shown below is executed many times before it randomly throws the index out of range exception:
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++;
}
}
}
As shown in the screenshot, the index at the moment of the exception was 499, and the array size is 500. I know I'm iterating through another buffer based on its size, but both the data and time buffers always have 500 elements. Any idea what might be causing the exception? Here is the code for the AddNewPoint
function:
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();
}
}
This doesn't happen all the time, so I'm considering just using a try statement so that the program can keep running when this exception happens occasionally.