views:

225

answers:

2

I have an ASP.NET application that caches some business objects. When a new object is saved, I call remove on the key to clear the objects. The new list should be lazy loaded the next time a user requests the data.

Except there is a problem with different views of the cache in different clients.

  • Two users are browsing the site
  • A new object is saved by user 1 and the cache is removed
  • User 1 sees the up to date view of the data
  • User 2 is also using the site but does not for some reason see the new cached data after user 1 has saved a new object - they continue to see the old list

This is a shortened version of the code:

public static JobCollection JobList
{
    get
    {
        if (HttpRuntime.Cache["JobList"] == null)
        {
                GetAndCacheJobList();
        }
        return (JobCollection)HttpRuntime.Cache["JobList"];
    }
}

private static void GetAndCacheJobList()
    {
        using (DataContext context = new DataContext(ConnectionUtil.ConnectionString))
        {
            var query = from j in context.JobEntities
                        select j;
            JobCollection c = new JobCollection();
            foreach (JobEntity i in query)
            {
                Job newJob = new Job();
                ....
                c.Add(newJob);
            }
            HttpRuntime.Cache.Insert("JobList", c, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
        }
    }

public static void SaveJob(Job job, IDbConnection connection)
    {
        using (DataContext context = new DataContext(connection))
        {

               JobEntity ent = new JobEntity();
               ...
               context.JobEntities.InsertOnSubmit(ent);                
               context.SubmitChanges();
               HttpRuntime.Cache.Remove("JobList");                                     

        }
    }

Does anyone have any ideas why this might be happening?

Edit: I am using Linq2SQL to retreive the objects, though I am disposing of the context.

A: 

That's because you don't synchronize cache operations. You should lock on writing your List to the cache (possibly even get the list inside the lock) and on removing it from the cache also. Otherwise, even if reading and writing are synchronized, there's nothing to prevent storing the old List right after your call to Remove. Let me know if you need some code example.

A: 

I would also check, if you haven't already, that the old data they're seeing hasn't been somehow cached in ViewState.

overslacked