Search code examples
c#iiscachingfile-iohttpmodule

How to cache reading from a file .NET 2.0


I have an httpmodule that reads from a csv file for redirection rules.

However, since it's an httpmodule and it is checking on every request, I obviously don't want to read the file every time.

What are some strategies to cache the rules (in an in Array) so that I do not have to read the file on every request?

Update: Using .NET 2.0


Solution

  • Use Cache with file dependency

    On cache miss you will read your values and also transform them into a list of certain object types and cache them. The benefits:

    • unified storage for all users, because they all these values since you're using HttpModule
    • automatic memory utilisation management - cache is fast and may get discarded when server is low on memory
    • file dependency cache is great when you change the file and your cache will automatically get invalidated and read anew in the first request from the newly changed file so you don't have to restart you application or do some other tricks to refresh cached values
    • fast data reads - if you also convert CSV data on file read you gain a lot of time because you will only parse it once so all subsequent data reads will take much less time than if you stored CSV raw data only and parse on every data read

    Additional note
    It should be noted as well that OS caches files as well. So if you frequently use certain files access will be quicker on consequent reads if they are done in a relative short time-frame. Relative because this depends on server load, memory usage etc. Just from the top of my head. But it would still be much slower than caching described.