Skip to content

Cache extension method does multiple initialization in parallel access #40

@rmaenk

Description

@rmaenk

Hello,

I have detected that Cache extention method does not implement thread-safe initialization.
In our app we are using WEB API and each route uses the same logic for validating access. This logic makes a query to DB to get large set of data. Cache extension helps us improve performance by avoiding this expensive query while data is not changed.

However, if query result is not in cache yet, then multiple requests may occur to DB for the same query.

In our case we are making 3 parallel calls to different WEB API routes( all of them uses the same query to get data for validation). In result in SQL Profiler we see 3 SQL queries instead of 1.
This occurs because processing of the query takes long time, 1-3 sec, and multiple requests to cache from different threads try to initialize the cache.

I have found a good article that describes the same issue in more details and provides interesting fix:
Working with System.Runtime.Caching.MemoryCache

What do you think about this?

From my point of view it would be good to have ability to avoid multiple cache initialization using the way suggested in the article.
It may be good to have separate implementation of Cache extension method from existing one or just add a parameter to existing, that switch internal behavior. Just to minimize side effects for existing applications.

Thanks,
Roman

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions