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

标签 c# .net entity-framework

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

    // 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.

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

最佳答案

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

关于c# - Entity Framework - 同时执行多个查询时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4940253/

相关文章:

c# - 图像绘制速度

.net - 异常代码 : 0xe0434f4d

c# - Visual Studio 2010 中的 "Browse To Find Source"

mysql - 首先在 WCF 服务中的何处为 EF6 代码设置 DbConfiguration?

.net - Entity Framework 与表示层分离

c# - 为什么位图保存为PNG

c# - 如何使用 C# 打开特定目录并在其中选择特定文件

c# - 无法在 MVC 中使用 EditorFoModel html 帮助程序显示数据

.net - 企业库 RangeValidator 语法

c# - 使用 MVC 3 Entity Framework 代码优先,如何在一对多关系中创建一个新的 "many"对象?