i'm developing an asp.net application. In my database i've a "classic" mono-record settings table. Each time i need a setting, i write some code like this
if ReturnSetting("my_setting") = value then
'do something
else
'do others
end if
In 'ReturnSetting' i open a connection, get the setting value and return it. This is not efficient (open connection, datareader etc.)
How can i optimize this ?
开发者_JAVA百科Thank you
you could write a variable and fill them only on the first request. The next requests will return the already filled variable.
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];
}
}
I think you can write the call to the function on the Global.asax file in the application start event to load this data once from the database and put the result in an application object and update your "ReturnSetting" function to check for the application object and this will optimize your code so that the database call is done once.
N.B. This solution will work effectively if this is global web site settings but if it is a user setting so you have to use the Session Start event in the global.asax and the session to store the data in.
精彩评论