1

I am thinking to use HttpContext.Current.Cache which has application level scope. I know that Cache object is thread safe but the thing that i don't understand is cached objects are not thread safe so how it is possible to use and modify them thread safely ???

AnyOne
  • 931
  • 2
  • 12
  • 40

3 Answers3

4

As per MSDN article the Cache type is thread safe but caching not thread safe object may cause unexpected errors.

Here is very good thread (stackoverflow) on Thread-safe cache libraries for .NET and MSDN article on Object Caching (Sharepoint) - Object Caching Techniques

Community
  • 1
  • 1
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
1

It is your own responsibility to make sure that the objects placed in the cache are thread-safe.

Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46
  • 1
    Exactly. Either objects should be thread-safe, or you should replace them completely by a new instance (threat them as immutable objects). Best is to *not* update parts of objects inside your cache. Just use read-only lists of immutable objects. – Steven Oct 12 '11 at 12:51
0

If different threads are going to use and modify the cached objects concurrently then you will need some application level protocol. This can be either as simple as lock(cachedObject) {....}

If you can determine that something in the cache is only accessed by a single thread at a time or that it cannot be modified (because it is immutable) then you don't need anything further.

What it means for HttpContext.Current.Cache to be threadsafe is that multiple threads can get and put stuff in it concurrently. So if you want some co-ordination between multiple keys then you will need some higher level locking.

Miserable Variable
  • 28,432
  • 15
  • 72
  • 133