eych
eych

Reputation: 1272

Making Cache access methods static

In ASP.NET, is there any reason not to make a set of functions that Add/Remove/Get from the Cache object Static?

Get() - just gets the item, no reason not to be static
Add(), Remove() - I've read that adding/deleting into the cache has it's own internal locking mechanism, so they can be static without me creating my own lock(){} wrapping.

Upvotes: 9

Views: 2826

Answers (1)

Chris Marisic
Chris Marisic

Reputation: 33118

They can already be accessed in a static context through

HttpRuntime.Cache

The method of HttpContext.Current.Cache merely forwards to this call anyway, yet invoking the HttpContext.Current.Cache can cause runtime errors if it's not in the lifecycle where HttpContext.Current is available.

Answering your question:

Yes you could use this to handle that. You would have something like

public static class StaticCache
{

    public static Add(object obj)
    {        
        try {            
            HttpRuntime.Cache.Add(obj);            
        }
        catch(Exception ex) {
            //log or something            
        }        
    }    
}

And usage would be similar to

StaticCache.Add("bob");

Upvotes: 10

Related Questions