我正在开发一个asp.net应用程序。在我的数据库中,我有一个“经典”单声道记录设置表。 每次我需要一个环境,我这样写如何“缓存”asp.net应用程序中的持久设置
if ReturnSetting("my_setting") = value then
'do something
else
'do others
end if
一些代码在“ReturnSetting”我打开一个连接,得到了设定值,并返回。 这是不高效的(开放连接,数据采集等)
我该如何优化?
谢谢
我正在开发一个asp.net应用程序。在我的数据库中,我有一个“经典”单声道记录设置表。 每次我需要一个环境,我这样写如何“缓存”asp.net应用程序中的持久设置
if ReturnSetting("my_setting") = value then
'do something
else
'do others
end if
一些代码在“ReturnSetting”我打开一个连接,得到了设定值,并返回。 这是不高效的(开放连接,数据采集等)
我该如何优化?
谢谢
我想你可以写调用在应用启动事件在Global.asax文件中的函数从数据库加载一次这些数据,并把结果在应用程序中的对象并更新“ReturnSetting”函数来检查应用程序对象,这将优化您的代码,以便数据库调用完成一次。
N.B.如果这是全局网站设置,则此解决方案将有效工作,但如果它是用户设置,则必须使用global.asax中的Session Start事件和会话来存储数据。
你可以写一个变量,并填写他们只在第一次请求。接下来的请求将返回已经填充的变量。
public static class Settings
{
internal static Dictionary<string, object> _settingsCache = new Dictionary<string, object>();
internal static Mutex _mutex = new Mutex();
public static object Get(string key)
{
_mutex.WaitOne();
if (_settingsCache[key] == null)
{
// add to the cache
_settingsCache.Add(key, NEW_DATA)
}
_mutex.ReleaseMutex();
return _settingsCache[key];
}
}
是的......你说得对。谢谢 ! – stighy
不客气! –