Skip to main content
 首页 » 编程设计

c#之Entity Framework之同时执行多个查询时出错

2024年02月23日17lyhabc

在我的应用程序中同时发生了两件事。计时器每隔几秒在后台线程中触发更新数据网格的请求。这是该线程运行的代码:

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

我遇到的问题是这两个代码块是同时执行的。我收到以下错误:

内部异常如下:

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

为什么并发数据库操作不能被 Entity Framework 或我正确处理,有什么想法吗?

请您参考如下方法:

Entity Framework 对象上下文不是线程安全的。确保你使用的上下文与你使用的每个线程不同——从你的示例代码中看不出你这样做,但这将是我对问题出在哪里的第一个猜测。