Can I make static variable lifetime end at end of execution?

129 views Asked by At

I am trying to create a menu dynamically the first time a user accesses my site as shown in the code below. The problem is that my static global variables lifetime is longer than execution time so if a users permissions as to which menu items they can access changes and execution ends and then starts again the old menu may still be stored in MainMenu and MenuGenerated=1 so they will see the old menu as the new one will not be generated.

Is there a different type of variable that I can use to solve this problem or is there a different way of doing this?

public static class Globals
{
    public static List<MenuItem> MainMenu = new List<MenuItem>();
    public static Int32 MenuGenerated = 0;
}

public partial class SiteMaster : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<MenuItem> MainMenu = Globals.MainMenu;
        if (Globals.MenuGenerated == 0)
        {
             //set MenuGenerated=1
             //Generate menu items based on permissions stored in SQL tables
             //store in global MainMenu
        }
        foreach (MenuItem i in MainMenu)
        {
            NavigationMenu.Items.Add(i);
        }
    }
 }
2

There are 2 answers

1
Servy On BEST ANSWER

Static variables are going to be shared between users, so that's not an appropriate place to cache a menu that's a per-user value.

You can use Session to store data in a context that will be shared between all of the requests of that user in their session.

If you want to store the data beyond the scope of the user's current session (since you're just caching a menu, I wouldn't expect you to need anything other than the session) you could either back your session with a database, instead of using an in-memory session implementation, or explicitly store the data in a database (without using Session). Of course, since the idea here is you trying to cache values, that wouldn't appear to be helpful in this context.

0
David W On

If you have a menu structure based on database-dependent values that are likely to change that suddenly/quickly, then the best choice may be to rebuild the menu on each round-trip, but that has drawbacks for scalability and performance. A design that focuses on generating the menu once, persisting it into the Session or the viewstate, and only rebuilding it on a new visit to the site (new session), would probably be a better first strategy to explore.