Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOutOfRangeException on Queryable.Single

Tags:

c#

linq

I have an ASP.NET site that has been running perfectly for a long time, nothing's changed recently. From one hour to the next I started receiving an IndexOutOfRangeException in a line where I do a LINQ query like this:

var form = SqlDB.GetTable<ORMB.Form, CDB>()
    .Where(f => f.FormID == formID)
    .Single();

ORMB.Form is a POCO object with LINQ to SQL attributes mapping it to an MSSQL table (mapping is verified as correct). The stacktrace is as follows:

System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Collections.Generic.List`1.Add(T item)
   at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
   at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
   at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
   at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
   at System.Linq.Queryable.Single[TSource](IQueryable`1 source)
   at GetForm.Page_Load(Object sender, EventArgs e)

Reflecting System.Collections.Generic.List.Add shows the following code:

public void Add(T item)
{
    if (this._size == this._items.Length)
    {
        this.EnsureCapacity(this._size + 1);
    }
    this._items[this._size++] = item;
    this._version++;
}

The only line that should be prone to the IndexOfOutRangeException is this._items[this._size++] = item, I cannot see how I'm affecting this however.

I can solve the problem by doing an appdomain recycle, so it must be caching related somehow. ObjectTracking is turned off on the DataContext, in case that matters.

My gut feeling is that this might be a threading issue, SqlConnectionManager having cached IConnectionUsers in the List field called 'users'. If two threads enter the Add method at the same time, what prevents the following from happening:

T1: Add(x)
T2: Add(y)
T1: Since _size == _items.Length: EnsureCapacity(_size + 1)
T2: Since _size > _items.Length: _items[_size++] = item;
T1: _items[size++] = item <- OutOfRangeException since T2 didn't increase the capacity as needed

Anyone?

like image 666
Mark S. Rasmussen Avatar asked Oct 16 '08 13:10

Mark S. Rasmussen


1 Answers

Are you sharing a common DataContext? That would explain the threading issues you are describing, as DataContext is not thread safe.

like image 115
csgero Avatar answered Oct 16 '22 08:10

csgero