c#缓存机制,用于大批量连接数据库的性能优化,可减少对数据库的消耗。

public void FrmReceive_Load(object sender, EventArgs e)//初始化加载
        {
            SqlDependency.Start(_connectionString);
            ModuleId = DBOperation.GetMouduleId(DbHelper, "废水");
            DataProcessing.ParamList = GetDataList(ModuleId);
          }


 public static List GetDataList(Guid moduleid)//开始加载数据库缓存
        {
            var list = new List();
            try
            {
                var sql =
                    $@"select *   from dbo.Param a where a.State = 0  ";
                if (string.IsNullOrEmpty(_connectionString))
                    _connectionString = Xml.Read("SysSet.xml", "ConnectionString").ToString();
                using (var connection = new SqlConnection(_connectionString))
                {
                    using (var command = new SqlCommand(sql, connection))
                    {
                        command.CommandType = CommandType.Text;
                        connection.Open();
                        var dependency = new SqlDependency(command);
                        dependency.OnChange += dependency_OnChange; //检测数据库变动
                        var sdr = command.ExecuteReader();
                        while (sdr.Read())
                        {
                            var model = new ParamModel
                            {
                                ParamId = Guid.Parse(sdr["ParamId"].ToString()),
                                ParamCode = sdr["ParamCode"].ToString(),
                                PollutionType_Id = Guid.Parse(sdr["PollutionType_Id"].ToString())
                            };
                            list.Add(model);
                        }
                        sdr.Close();
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.LogError(e);
            }
            return list;
        }
        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)//存在数据库任一变动,重新拉取缓存数据
        {
            var t1 = new Task(LoadCacheData); //task数据拉取。
            t1.Start();
        }
        private static void LoadCacheData()//拉取缓存
        {
            DataProcessing.ParamList = GetDataList(ModuleId);
        }
dependency_OnChange 为自动监测数据库变化引发的数据更新,但是只能针对单表进行监测,所以在该机制的局限下,不支持多表的联合查询。

你可能感兴趣的:(c#缓存机制,用于大批量连接数据库的性能优化,可减少对数据库的消耗。)