ASP.NET初始化数组

时间:2016-02-18 20:25:03

标签: asp.net arrays webforms initialization

我的网站包含1000个对象的数组(列表),这些对象从json加载到每个网站刷新的数组。我想将这些对象从json加载到数组只有一次,并将其保存在RAM中供其他用户使用。因为每次读取文件比从RAM读取文件慢得多。

我正在使用ASP.NET Web Forms

怎么可能?

2 个答案:

答案 0 :(得分:0)

我建议将数组定义为类的静态成员,然后在Global.asax的帮助下初始化它,使用Application_Start事件处理程序。

在Visual Studio中将Global.asax添加到项目中:

File -> New -> File -> Global Application Class

以下是Global.asax.cs的示例C#代码:

public class Global : HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        //  ... Your initialization of the array done here ...
    }

    protected void Session_Start(object sender, EventArgs e)
    {
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
    }

    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
    }

    protected void Application_Error(object sender, EventArgs e)
    {
    }

    protected void Session_End(object sender, EventArgs e)
    {
    }

    protected void Application_End(object sender, EventArgs e)
    {
    }
}

答案 1 :(得分:0)

这些值是静态的,即它们在您的应用程序运行时是否保持不变?在这种情况下,最简单的方法是缓存这些值。

can use static variables for that,但推荐的方法是使用ASP.NET提供的线程安全的Cache对象。可以使用Cacheof the HttpContextPage属性访问它。

示例:

var myList = (MyListType)Cache["MyList"];
if (myList == null)
{
    myList = ...;              // Load the list
    Cache["MyList"] = myList;  // Store it, so we don't need to load it again next time.
}

进一步阅读: