Alex Rivera | Logout

Using a static variable to cache data

Asked 2009-06-08T22:19:02.287
12

We're developing a .NET 3.5 Windows Forms app, using LINQ to SQL and MVP. We have a DataRepository class for retrieving data:

public class DbUserRepository : IUserRepository 
{
  private IList<UserName> _users;

  public IList<UserName> GetUserNames()
  {
    if (_users == null)
    {
      // retrieve _users from DB
    }

    return _users;
  }

In order to cache the list of users across all instances of the DBUserRepository, we were going to use the Enterprise Library's Caching Application Block.

But it occured to me, couldn't I just make _users a static member? For some reason that seems like an "old school" way, but it works. Are there any downsides to doing this? Is this considered bad design?

private static IList<UserName> _users;

Thanks

c#
Edit
Report

1 Answer

3

for simple caching I think static variable is fine, just need to be a bit careful about using locks to protect multiple threads accessing the _users variable. However, a better approach might be using ASP.NET Cache class. I know it is in the System.Web namespace but you can use it outside of ASP.NET application too.

answered 2009-06-08T22:27:27.513

Your Answer