2011-02-09 65 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