MemoryCache to optimize database lookups.


The following code snippet displays a method of using a memory cache for generic types.

Because there are plenty of examples of using MemoryCache we have included a example below.

In this example performance is increased by putting the object into cache (which happens to be a row of data from a database), if that data is not accessed within a sliding expiration time (in this example 1 minute) it will be removed from the memory cache and if accessed later will re fetch from the database and once again place it in the cache.


Generic MemoryCache

Imports System
Imports System.Runtime.Caching

Namespace GenericCache
    Module Caching
        Function GetObjectFromCache(Of T)(ByVal cacheItemName As StringByVal cacheTimeInMinutes As IntegerByVal objectSettingFunction As Func(Of T), ByRef isCached As BooleanAs T
            Dim cache As ObjectCache = MemoryCache.[Default]

            Dim cachedObject = CType(cache(cacheItemName), T)

            If cachedObject Is Nothing Then
                Dim policy As CacheItemPolicy = New CacheItemPolicy()
                'policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(cacheTimeInMinutes) ' Fixed Timeout
                policy.SlidingExpiration = TimeSpan.FromMinutes(cacheTimeInMinutes) ' Sliding timeout
                cachedObject = objectSettingFunction()
                isCached = False
                cache.[Set](cacheItemName, cachedObject, policy)
                isCached = True
            End If

            Return cachedObject
        End Function

    End Module

End Namespace


Dim FetchfromDatabase As Func(Of IPAddressLookup= AddressOf dbFetch

   Private Function dbFetch() As IPAddressLookup
       Using db As New MyDBDataContext
           Dim result = (From this In db.IPAddressLookups Where this.IPAddress = "").ToList
           If result.Count > 0 Then
               Dim rtn = result.First
               rtn.LastAccess = Now
               Return rtn
           End If
       End Using
       Return Nothing
   End Function


Dim isCached As Boolean
Dim IPAddressResult As IPAddressLookup = GetObjectFromCache(Of IPAddressLookup)("IPAddressResult"1, FetchfromDatabase, isCached)

In the above example IPAddressResult will be either the cached data row or newly fetched data row depending on whether it was recently accessed within the sliding expiry period or not.


The example can be used in or Windows Forms applications.

Article Rating:
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)