Application
is a data warehouse left over from old ASP technology. It has one global castle. When you call Application.Lock()
, all calls to the Application object in all threads are blocked.
On the other hand, the new Cache
object that was introduced using ASP.NET allows you to use your own locking semantics. You can use the .NET lock
statement to provide stream access to the Cache object, while keeping your web application as parallel as possible. The lock
statement is much safer, because the lock is guaranteed to be released when the lock
block exits. The application object does not guarantee this. The cache also provides automatic expiration mechanisms that are much more suitable for the cache. It can also expire keys based on dependency contracts and optional priorities, which, of course, are not in the Application object.
I see no reason to use Application
over the Cache
object.
Example. Let's say you have one hundred items in the cache, and you have one item that you want to keep in the cache if it does not already exist. When you use Application
, you do this:
if(Application["someData"] == null) { Application.Lock(); if(Application["someData"] == null) { Application["someData"] = getValue();
In this scenario, all calls to the application object are blocked, even if they are completely irrelevant. And in case getValue()
throws an exception, your application freezes because the lock is not released. You need to wrap a try
.. finally
around it to make sure it is safe.
On the other hand, when using the Cache
object, you do this:
if(Cache["someData"] == null) { lock(myLockObject) // or other shared lock for that single value { if(Cache["someData"] == null) { Cache["someData"] = getValue(); } } }
In this case, only code blocks are expected that require access to myLockObject
. Others that have access to Cache
will work in parallel. And in case getValue()
throws an exception, your lock will be released without any problems, allowing other threads to continue executing.