如果我得到这样的值:
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/