ASP.NET维护静态变量 [英] ASP.NET maintaining static variables

查看:96
本文介绍了ASP.NET维护静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我们了解了IIS的AppDomain回收以及如何影响将它们设置为主要值(空,0等)的静态变量.

Recently we learned about AppDomain Recycling of IIS and how it affects static variables setting them to their primary values (nulls, 0s, etc).

我们使用一些在静态构造函数中初始化的静态变量(对于首次初始化,从数据库中检索到的配置值例如小数位数",管理员电子邮件"等...)它们在网站执行过程中的价值.

We use some static variables that are initialized in a static constructor (for first time initialization, configuration values like "number of decimal places", "administrator email", etc... that are retrieved from DB) and then only read their value along the website execution.

解决此问题的最佳方法是什么?一些可能的想法:

Whats the best way of solving this problem? Some possible ideas:

  • 在每次检索时检查变量是否为null/0(由于可能的性能影响+将检查添加到每个变量所花费的时间+添加到项目中的代码重载,所以不喜欢它)

  • Checking if variable is null/0 at each retrieval (don't like it because of a possible performance impact + time spent to add this check to each variable + code overload added to the project)

以某种方式防止AppDomain回收(这种重置逻辑不会在具有静态变量的Windows窗体中发生,难道它在两种环境中都不能像相同的语言一样工作吗?至少在标准方面类似于静态变量管理))

Somehow preventing AppDomain Recycling (this reset logic doesn't happen in Windows forms with static variables, shouldn't it work similarly as being the same language in both environments? At least in terms of standards as static variables management)

使用其他方式保存这些变量(但我们认为,对于某些信息(用作所有用户的全局引用)而言,静态变量是性能/编码方面的最佳选择)

Using some other way of holding these variables (but we think that for being some values used for info as global reference for all users, static variables were the best option performance/coding wise)

订阅那些在AppDomain回收中触发的事件,以便我们可以重新初始化所有这些变量(如果无法避免回收,这可能是最好的选择...)

Subscribing to an event that is triggered in those AppDomain Recycling so we can reinitialize all those variables (maybe best option if recycling can't be prevented...)

想法?

推荐答案

检查包装在代码中的null:

Checking the null wrapped into code:

public interface IMyConfig {
  string Var1 { get; }
  string Var2 { get; }
}

public class MyConfig : IMyConfig {
  private string _Var1;
  private string _Var2;

  public string Var1 { get { return _Var1; } }
  public string Var2 { get { return _Var2; } }

  private static object s_SyncRoot = new object();
  private static IMyConfig s_Instance;

  private MyConfig() {
    // load _Var1, _Var2 variables from db here
  }

  public static IMyConfig Instance {
    get {
      if (s_Instance != null) {
        return s_Instance;
      }
      lock (s_SyncRoot) {
        s_Instance = new MyConfig();
      }
      return s_Instance;
    }
  }
}

这篇关于ASP.NET维护静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆