Imports System.Runtime.Caching
Namespace Caching.Generic
Public Class MyMemoryCache
Private MyCache As MemoryCache
Public ReadOnly Property Count As Integer
Get
Return MyCache.Count
End Get
End Property
Public ReadOnly Property Cache As MemoryCache
Get
Return MyCache
End Get
End Property
Public Sub New(Domain As String, Optional CacheMemory As Integer = 0, Optional PhysicalMemoryLimit As Long = 0, Optional PollingIntervalMinutes As Integer = 2)
If PhysicalMemoryLimit > 100 Then PhysicalMemoryLimit = 100
Dim cachesetting As New NameValueCollection
cachesetting.Add(“CacheMemoryLimitMegabytes”, CacheMemory)
cachesetting.Add(“physicalMemoryLimitPercentage”, PhysicalMemoryLimit)
cachesetting.Add(“pollingInterval”, TimeSpan.FromMinutes(PollingIntervalMinutes).ToString())
cachesetting.Add(“Name”, Domain)
MyCache = New MemoryCache(Domain, cachesetting)
End Sub
Public Function GetObjectFromCache(Of T)(ByVal cacheItemName As String, ByVal cacheTimeInMinutes As Integer, ByVal objectSettingFunction As Func(Of String, T), ByRef isCached As Boolean, ByRef AccessTime As Long) As T
Dim sw As New Stopwatch
sw.Start()
Dim cachedObject = CType(MyCache(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(cacheItemName)
isCached = False
MyCache.[Set](cacheItemName, cachedObject, policy)
Else
isCached = True
End If
sw.Stop()
AccessTime = sw.ElapsedMilliseconds
Return cachedObject
End Function
End Class
End Namespace
Using Generic MemoryCache
Dim results As IPAddressLookup
Using db As New ServerDefenderDBDataContext
results = (From this In db.IPAddressLookups Where this.IPAddress = key Take 1).SingleOrDefault
End Using
Return results
End Function
Dim AccessTime As Long
Dim IPAddressResult As IPAddressLookup = IPAddressCache.GetObjectFromCache(Of IPAddressLookup)(ComboBox1.SelectedItem, 10, FetchfromDatabase, isCached, AccessTime)




