Do not cache Web ListItems

In our ASP.NET application we have DropDownLists with standard values from reference data(e.g list of Countries).
And we used Cache to avoid re-loading them from the database. The function was like the following:
            private void LoadItems()
            {
                  ListItem[] cachedItems;
                  cachedItems = GetAppCacheItems();
                  if (cachedItems == null)
                  {
                        //Load the reference data from the database omitted for simplicity
                        SetAppCacheItems(cachedItems);
                  }
                  Items.Clear();
                  Items.AddRange(cachedItems);
            }
 And this method worked for a long time. Unfortunately, some users complained that sometimes combo-boxes showed values, different from what they selected. Delelopers tried to reproduce the problem on the development machines without success.
I've wrote Watin test case trying to reproduce the problem, and it helped me to find the cause.
ListItem includes Selected  property and keeping it in a cache effectilely shares the selection between all users. If one user selected AU as country, but other user selected US at the same time, the  first user can see US as his selection.
I had to change code to recreate ListItems for each request.
It is still a good idea to keep returned from database data as Dataset or other collection in a cache(For example see Peter A. Bromberg's article VB.Net: Database/xml enabled, self-cacheing, TooltipDropDownList ServerControl orMichael Thomas's Custom auto-bound Drop Down List post).

posted @ Friday, September 07, 2007 2:15 PM

Print

Comments on this entry:

# re: Do not cache Web ListItems

Left by Jeroen van Menen at 9/14/2007 7:24 AM
Gravatar
Hi Michael,

Nice to read that WatiN helped you locate and solve the issue!

Jeroen van Menen
Lead dev WatiN

# re: Do not cache Web ListItems

Left by lws at 11/12/2007 6:59 AM
Gravatar
I think you SHOULD cache listitems. Just put them in the cache before the selected is set, and only load the drop downs if not posted back. The viewstate takes care of the contents of the drop down on post back.

# re: Do not cache Web ListItems

Left by Michael Freidgeim at 11/12/2007 11:31 PM
Gravatar
Lws,
The objects in cache are shared between all users. When individual listbox is constructed, it is nesessary to create clones of ListItems or new listItems. But ListItemCollection.AddRange keeps references to the same ListItem objects. And changing the ListItem object by assigning Selected value affects all users, who has references to the item.

Your comment:



 (will not be displayed)


 
 
 
Please add 5 and 5 and type the answer here:
 

Live Comment Preview:

 
«December»
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910