2011-02-09 47 views
1

在我的应用程序中一次执行两件事。定时器在后台线程中每隔几秒触发一次请求更新数据网格。下面是由线程运行的代码:实体框架 - 同时执行多个查询时出错

// 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>(); 

现在,在UI线程,还有另一种形式打开正在更新的位置网格:

/// <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"; 

} 

我的问题当两个代码块都在同一时间执行时。我得到以下错误:

enter image description here

内部异常如下:

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

为什么并发数据库操作都不会被实体框架正确处理任何想法----或者我?

回答

4

实体框架对象上下文不是线程安全的。确保你使用的每个线程都使用了不同的上下文 - 从你的示例代码中不清楚你做了什么,但这是我第一次猜测问题出在哪里。

+0

你是对的。我不知道他们不是线程安全的。谢谢! – 2011-02-09 01:23:58