c#-4.0 - AppSetting 值是从内存还是从 web.config 文件中读取的?

标签 c#-4.0 asp.net-mvc-4

如果我得到这样的值:

string value = ConfigurationManager.AppSettings["Key"];

我期望 .Net(在我的例子中是 MVC4)在应用程序域启动时解析了应用程序设置,而我实际上是从内存中读取。

如果不是这种情况,并且每次都会命中文件,那么在获取 AppSettings 时是否可以保证线程安全?

快速尝试锻炼我的 Google-Fu 失败了。

我倾向于使用这种机制来填充构造函数中的实例字段,因此:

public class MyThing 
{
  private readonly string thingValue;

  public MyThing() 
  {
    thingValue = ConfigurationManager.AppSettings["Key"];
  }
}

我们最近遇到了一个外部依赖项失败的场景,因为它们存在竞争条件并且“无法读取配置设置”。

这让我想知道:

  • AppSettings 是线程安全的吗?
  • 只读字符串模式是否提供了足够的保护?

最佳答案

而且,就像经常发生的情况一样,几乎在我问这个问题的同时,我的 google-fu 就启动了:/

MSDN lists the AppSettings method作为

public static NameValueCollection AppSettings { get; }

但实际上并没有提到线程安全。

然而,the page for the ConfigurationManager class有一个关于线程安全的部分说:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

所以看来我列出的机制是线程安全的。不过,我仍然有兴趣了解替代方法!

关于c#-4.0 - AppSetting 值是从内存还是从 web.config 文件中读取的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19421937/

相关文章:

c# - 通过来自 Controller 的查询查看与 FK 连接的多个模型

c# - 转换 WebMatrix DynamicRecord 或检索底层 IDictionary<string,object>

c# - 为什么 0.ToString ("#.##") 返回一个空字符串而不是 0.00 或至少为 0?

c# - 如何在单击交叉按钮时使 bool 值为 false?

.net - 如何防止类中的属性不存储在 session 中

c# - LESS 到 CSS 的转换是在客户端还是在服务器端完成的?

multithreading - WCF服务契约实现中的多线程操作

sql-server-2008 - 集成 SQL Service Broker 和 NServiceBus

asp.net-mvc - 使用 html.ActionLink 时如何在我的网址中添加 "#"

asp.net-mvc - 有没有办法将 Html.BeginForm 集中设置为 autocomplete=off?