Introduction
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 VB.net 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.Runtime.Caching
Namespace GenericCache
Module Caching
Function GetObjectFromCache(Of T)(ByVal cacheItemName As String, ByVal cacheTimeInMinutes As Integer, ByVal objectSettingFunction As Func(Of T), ByRef isCached As Boolean) As 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)
Else
isCached = True
End If
Return cachedObject
End Function
End Module
End Namespace
Implementing
Private Function dbFetch() As IPAddressLookup
Using db As New MyDBDataContext
Dim result = (From this In db.IPAddressLookups Where this.IPAddress = "192.168.0.1").ToList
If result.Count > 0 Then
Dim rtn = result.First
rtn.LastAccess = Now
Return rtn
End If
End Using
Return Nothing
End Function
Fetching
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 asp.net or Windows Forms applications.





