Mark T
Mark T

Reputation: 823

trying to Cache data in C# web service

I'm trying to use the using System.Web.Caching.Cache object but when I write Cache[key] I get syntax error:

System.Web.Caching.Cache is a type but used like a variable

can you help me solve the problem ? I'm using framework 4.

Upvotes: 1

Views: 5592

Answers (1)

Steven de Salas
Steven de Salas

Reputation: 21497

I think you want to use:

string value = HttpContext.Current.Cache[key] as string;

or:

HttpContext.Current.Cache.Insert(key, value);

or even this - but I recommend the .Insert() method above because you can set a timeout:

HttpContext.Current.Cache[key] = value;

The reason why .NET is complaining is because you are trying to use a class like an object (hence the message). The Cache property of HttpContext.Current will return an object of class System.Web.Caching.Cache which contains the current cache for your web service application (as opposed to a different cache item or the type-definition for all cache items).

NOTE: On a bit of an aside, bear in mind that if your code is going to be run in paralell machines (ie, on a server farm or 'cloud' architecture), the Cache contained in one machine will differ from the one contained in another machine. This will do fine if you're just building read-only output for fast response and are not too bothered when it gets disposed of, but if you're relying on clearing the cache for updates to your service output so you may want to use a different method to store your data as you may find it hard to pass the message along to other machines when the cache should be cleared in all of them.

Upvotes: 2

Related Questions