假设我有一个用于在网络应用程序上导航的类别列表。我应该在 global.asax 的 application_onStart 中添加一个函数调用来将该数据提取到反复重复使用的数组或集合中,而不是从数据库中为每个用户进行选择。如果我的数据根本没有改变 - (编辑 - 经常),这会是最好的方法吗?

有帮助吗?

解决方案

您可以将列表项存储在应用程序对象中。你是对的 application_onStart(), ,只需调用一个方法来读取数据库并将数据加载到 Application 对象。

在 Global.asax 中

public class Global : System.Web.HttpApplication
{
    // The key to use in the rest of the web site to retrieve the list
    public const string ListItemKey = "MyListItemKey";
    // a class to hold your actual values. This can be use with databinding
    public class NameValuePair
    { 
        public string Name{get;set;} 
        public string Value{get;set;}
        public NameValuePair(string Name, string Value)
        {
            this.Name = Name;
            this.Value = Value;
        }
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        InitializeApplicationVariables();
    }


    protected void InitializeApplicationVariables()
    {
        List<NameValuePair> listItems = new List<NameValuePair>();
        // replace the following code with your data access code and fill in the collection
        listItems.Add( new NameValuePair("Item1", "1"));
        listItems.Add( new NameValuePair("Item2", "2"));
        listItems.Add( new NameValuePair("Item3", "3"));
        // load it in the application object
        Application[ListItemKey] = listItems;
    }
 }

现在您可以在项目的其余部分访问您的列表。例如,在 default.aspx 中加载 DropDownList 中的值:

<asp:DropDownList runat="server" ID="ddList" DataTextField="Name" DataValueField="Value"></asp:DropDownList>

在代码隐藏文件中:

protected override void OnPreInit(EventArgs e)
{
    ddList.DataSource = Application[Global.ListItemKey];
    ddList.DataBind();
    base.OnPreInit(e);
}

其他提示

如果它永远不会改变,那么它可能不需要存在于数据库中。

如果数据不多,您可以将其放在 web.config 中,或者作为代码中的 en Enum 。

获取全部可能会很昂贵。尝试惰性初始化,仅获取请求数据,然后将其存储在缓存变量中。

过早的优化是邪恶的。既然如此,如果您的应用程序遇到性能问题,并且您有想要向用户显示的“静态”信息,您绝对可以将该数据加载到数组中并将其存储在应用程序对象中。您需要小心并平衡内存使用和优化。

然后您遇到的问题是更改数据库存储的信息,而不是让它更新缓存的版本。您可能希望在数据库中拥有某种上次更改的日期,并将其与缓存的数据一起存储在状态中。这样你就可以查询最大变化时间并进行比较。如果它比你的缓存日期新,那么你转储它并重新加载。

在应用程序变量中。

请记住,应用程序变量可以包含.Net中的对象,因此您可以在global.asax中实例化该对象,然后直接在代码中使用它。

由于应用程序变量位于内存中,因此速度非常快(与必须调用数据库相比)

例如:

// Create and load the profile object
x_siteprofile thisprofile = new x_siteprofile(Server.MapPath(String.Concat(config.Path, "templates/")));
Application.Add("SiteProfileX", thisprofile);

我会将数据存储在应用程序缓存(缓存对象)中。我不会预加载它,我会在第一次请求时加载它。缓存的优点在于 ASP.NET 将管理它,包括为您提供在文件更改、时间段等后使缓存条目过期的选项。由于项目保存在内存中,因此对象不会被序列化/反序列化,因此使用速度非常快。

用法很简单。Cache 对象有 Get 和 Add 方法,分别用于检索项目和将项目添加到缓存中。

我使用静态集合作为私有集合,并具有公共静态属性,该属性可以从数据库加载或获取它。

此外,您可以添加一个静态日期时间,该日期时间在加载时设置,如果您调用它,超过一定时间后,清除静态集合并重新查询它。

缓存是必经之路。如果您喜欢设计模式,请看一下单例。

但总的来说,在您注意到性能下降之前,我不确定我是否会担心它。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top