I'm trying to create an instance of the MemoryCache class in order to cache some document information. Problem is that even though I don't get any exceptions the MemoryCache instance always returns 'Nothing'. I'm using the following bits of code;
Constructing the instance:
Private Shared ObjInfoCache As MemoryCache
Public Sub New()
Dim CacheSettings As NameValueCollection = New NameValueCollection(3)
CacheSettings.Add("CacheMemoryLimitMegabytes", 1024.ToString())
CacheSettings.Add("physicalMemoryLimitPercentage", 50.ToString())
CacheSettings.Add("pollingInterval", TimeSpan.FromMinutes(2).ToString())
ObjInfoCache = New MemoryCache("TestCache", CacheSettings)
End Sub
Code that saves/retrieves the information (which always jumps into the if statement):
arrayOfPropValues = ObjInfoCache(docID)
If arrayOfPropValues Is Nothing Then
arrayOfPropValues = GetDocumentInfo(docID, arrayOfPropNames)
ObjInfoCache.Add(docID, arrayOfPropValues, New CacheItemPolicy() With {.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60)})
End If
Through testing I've found that using the default MemoryCache instance ObjInfoCache = MemoryCache.Default
works perfectly. It however doesn't let me set the limit properties, which I'll need. I've also tried creating a new MemoryCache instance without adding the settings ObjInfoCache = new MemoryCache("TestCache")
, which still returns Nothing.
I'm using .NET Framework 4
About the return; I meant it returned Nothing when calling a variable from the cache instance
I suspect that you are creating multiple instance of the class that defines ObjInfoCache.
You have declared ObjInfoCache
as Shared
, thus its reference is common to all instances of the class. However, you are initializing this reference in the class instance constructor (Public Sub New()). Change the constructor to be Shared
so that it only executes once when the type is referenced.
Shared Sub New()
Dim CacheSettings As NameValueCollection = New NameValueCollection(3)
CacheSettings.Add("CacheMemoryLimitMegabytes", 1024.ToString())
CacheSettings.Add("physicalMemoryLimitPercentage", 50.ToString())
CacheSettings.Add("pollingInterval", TimeSpan.FromMinutes(2).ToString())
ObjInfoCache = New MemoryCache("TestCache", CacheSettings)
End Sub