1. 程式人生 > >事務(程序 ID 66)與另一個程序被死鎖在 鎖 資源上,並且已被選作死鎖犧牲品。請重新執行該事務

事務(程序 ID 66)與另一個程序被死鎖在 鎖 資源上,並且已被選作死鎖犧牲品。請重新執行該事務

做Silverlight+domainservice+EF程式時,介面實時刷新出現的一個問題。


這個介面中的這幾個列表都是訪問同一個資料表,每隔10秒訪問一次。所以就在執行一段時間的時候出現死鎖的情況

查了查產生死鎖的原因,常見的死鎖情況,修改了一下程式碼

  #region 得到圍巖應力感測器的實時資料
        /// <summary>
        /// 得到圍巖應力感測器的實時資料
        /// </summary>
        /// <returns></returns>
        public List<CurrentData> GetBoreholeSensorCurrentDataList(int WorkingFaceID, int UserID)
        {
            List<CurrentData> list = new List<CurrentData>();
            MyTool.NoLockInvokeDB(() =>
            {
                if (UserID == 0)
                {
                    list = db.CurrentDatas.Include("Sensor").Where(p => p.Sensor.SensorType == 4 && p.Sensor.Livestate == 0 && p.Sensor.WorkingFaceID == WorkingFaceID).ToList();
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    SysUser u = db.SysUsers.FirstOrDefault(p => p.UserID == UserID);
                    List<Sensor> listSensor = u.Sensors.Where(p => p.SensorType == 4).ToList();
                    StringBuilder sb_ZB = new StringBuilder();
                    sb.Append(" and it.Sensor.SensorType = 4 and it.Sensor.Livestate=0");
                    sb.Append(" and it.Sensor.WorkingFaceID = " + WorkingFaceID + "");
                    if (listSensor.Count > 0)
                    {
                        foreach (var item in listSensor)
                        {
                            // sb_ZB.Append("'");
                            sb_ZB.Append(item.ID);
                            // sb_ZB.Append("'");
                            sb_ZB.Append(",");
                        }


                        string zbList = sb_ZB.ToString().Substring(0, sb_ZB.ToString().Length - 1);


                        sb.Append(" and it.SensorID in {" + zbList + "}");
                        list = db.CurrentDatas.Include("Sensor").Where(sb.ToString().Substring(4)).ToList();
                    }//等於0說明該普通使用者沒有改型別下的感測器


                }
            });

            return list;
        }
        #endregion

----------------------

namespace SDSUCCEEDKJ24.Web.Service
{
    public static class MyTool
    {
        public static void NoLockInvokeDB(Action action)
        {
            var transactionOptions = new System.Transactions.TransactionOptions();
            transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions))
            {
                try
                {
                    action();
                }
                finally
                {
                    transactionScope.Complete();
                }
            }
        }
    }
}

去掉lock。目前正在測試,希望有用。因為邏輯沒錯,次序一樣。只能這樣了,只是查詢而已了。