Search code examples
c#wpfexceptionlivecharts

C# Strange Instance of 'System.ArgumentOutOfRangeException'


I am using a LineSeries for drawing a chart from the library LiveCharts.Wpf by Beto Rodriguez. I am sending values to the chart which it draws and updates accordingly. I have a SeriesCollection to which I add the values based on a counter and also remove some values , as for example this :

if (_counter > 2 )
{
    SeriesCollection[3].Values[_counter-2] = double.NaN;   
}

So if the counter equals to something more than 2 , I set the value to NaN, that is I erase a point from the chart.

The problem is, at random times , I get a System.ArgumentOutOfRangeException and it says

Index was out of range. Must be non-negative and less than the size of the collection.

at the point where the value is being set to NaN and the debugger shows that the counter is equal to 0.

Obviously I am not allowing to execute this code when the counter is equal or less than 2 by this if (_counter > 2 ) condition, so how could this exception occur at this particular point?

EDIT : This question is not about what a 'System.ArgumentOutOfRangeException' is, as pointed out in the duplicate question, rather it was about how come this error was occurring in spite of checking for it in advance. Basically the value of _counter is being set to an unexpected value somewhere else in the code due to multi threading and that was the main issue. SeriesCollection[3] has nothing to do with the exception, and if anyone thinks so, I suggest checking out what this data type actually means from the LiveCharts library itself.


Solution

  • There is certainly another thread that changes the value of _counter between checking

    if (_counter > 2)
    

    and using it in

    Values[_counter - 2]
    

    A safer implementation would access it only once:

    var i = _counter - 2;
    
    if (i >= 0)
    {
        SeriesCollection[3].Values[i] = double.NaN;
    }