Jesse Bunch
Jesse Bunch

Reputation: 6679

Entity Framework - Error when multiple queries are executed at the same time

There are two things going on at once in my application. A timer fires off a request to update a data grid every few seconds in a background thread. Here is the code that is run by that thread:

    // Query
    var qryPickupRequests = from pr in objDataContext.pickupRequests
                                .Include("toLocation")
                                .Include("fromLocation")
                                .Include("person")
                            orderby pr.creationDate ascending
                            select pr;

    // Refresh from server?
    if (boolRefreshFromServer)
        (qryPickupRequests as ObjectQuery).MergeOption = MergeOption.PreserveChanges;

    // Limit?
    if (intLimit > 0)
        return qryPickupRequests.Take(intLimit).ToList<pickupRequest>();
    else
        return qryPickupRequests.ToList<pickupRequest>();

Now, in the UI thread, there is another form open that is updating a grid of locations:

/// <summary>
/// Refreshes the specified location data grid
/// </summary>
/// <param name="sender">Instance of GridLookupEdit to update</param>
private static void RefreshLocations(object sender) {

    GridLookUpEdit objEditor = sender as GridLookUpEdit;

    objEditor.Properties.DataSource = BRData.Models.LocationModel.GetLocationList(true);
    objEditor.Properties.DisplayMember = "locationName";
    objEditor.Properties.ValueMember = "locationID";

}

The issue I'm having is when both of these code blocks are executed at the exact same time. I get the following error:

enter image description here

The inner exception is as follows:

There is already an open DataReader associated with this Connection which must be closed first.

Any ideas why concurrent database operations are not handled correctly by the Entity Framework----or by me?

Upvotes: 1

Views: 825

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160892

Entity framework object contexts are not thread-safe. Make sure you use a different context from each thread you use - it's not clear from your example code that you do, but this would be my first guess on where the problem is.

Upvotes: 4

Related Questions