How to invalidate a single data item in the .net cache in VB
I have the following VB.NET code to set and read objects in cache on a per user basis (i.e. a bit like session)
Public Shared Sub CacheSet(ByVal Key As String, ByVal Value As Object)
Dim userID As String = HttpContext.Current.User.Identity.Name
HttpContext.Current.Cache(Key & "_" & userID) = Value
End Sub
Public Shared Function CacheGet(ByVal Key As Object)
Dim returnData As Object = Nothing
Dim userID As String = HttpContext.Current.User.Identity.Name
returnData = HttpContext.Current.Cache(Key & "_" & userID)
Return returnData
End Function
I use these functions to hold user开发者_如何学C data that I don't want to access the DB for all the time. However, when the data is updated, I want the cached item to be removed so it get created again.
How do I make an Item I set disappear or set it to NOTHING or NULL?
Taking an item out of the cache is as simple as calling HttpContext.Current.Cache.Remove(Key)
so in your case you'd probably want:
Public Shared Sub CacheRemove(ByVal key As String)
Dim userID As String = HttpContext.Current.User.Identity.Name
HttpContext.Current.Cache.Remove(Key & "_" & UserID)
End Sub
Since you say that when the data is updated you want the cached item to be removed so it gets re-cached with the updated data, you might want to take a look at using a SqlCacheDependency object. This wires up the cache to your database so that when your data changes, the cached item is automatically updated to keep it in sync.
精彩评论