ConfigurationManager.AppSettings Caching

旧城冷巷雨未停 提交于 2019-11-29 04:35:56

问题


We know that IIS caches ConfigurationManager.AppSettings so it reads the disk only once until the web.config is changed. This is done for performance purposes.

Someone at:

http://forums.asp.net/p/1080926/1598469.aspx#1598469

stated that .NET Framework doesn't do the same for app.config, but it reads from the disk for every request. But I find it hard to believe, 'cause it would be slower. Please tell me that he is wrong or I'll have to fix every Console/Windows Forms/Windows Services I wrote.

Update I regret that I misinterpreted what people said in the linked forum above.


回答1:


A quick test seems to show that these settings are only loaded at application startup.

//edit the config file now.
Console.ReadLine();

Console.WriteLine(ConfigurationManager.AppSettings["ApplicationName"].ToString());
Console.WriteLine("Press enter to redisplay");

//edit the config file again now.
Console.ReadLine();
Console.WriteLine(ConfigurationManager.AppSettings["ApplicationName"].ToString());
Console.ReadLine();

You'll see that all outputs remain the same.




回答2:


It reads the application configuration file (MyApp.exe.config) once at application startup, as can easily be verified by changing the file while the app is running.

The comment in the forum post referenced by the OP was:

The values for the Web.config are stored into cache/memory when the application starts hence why the app restarts when any changes are made to the web.config. Note that this only applies to the Web.config, any other .config files you may use are accessed from the disk by default

I would interpret this comment as meaning that config files other than web.config in an ASP.NET application are accessed from the disk by default. And similarly, config files other than MyApp.exe.config in a WinForms/Console application are accessed from the disk by default.

This comment is not stating that MyApp.exe.config is read from the disk by default.




回答3:


It doesn't matter if it does or not. Don't fix a performance problem if there isn't one.




回答4:


As John says only spend more time on this if you are actually seeing a performance hit.

Also I'm pretty sure that these applications hold the configuration in memory, and to see any changes within a config the application would have to be restarted.

For some further reading about remaining mysteries.




回答5:


AppSettings is cached. You can improve performance by further caching to limit namevaluecollection lookups.

See: DotNetPearls Static Config Pattern




回答6:


Try it,

ConfigurationManager.RefreshSection("appSettings")

Just be careful file name (in bin folder)

Normal file name : appname.exe.config

if debug mode : appname.vshost.exe.Config



来源:https://stackoverflow.com/questions/389361/configurationmanager-appsettings-caching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!