如何在VB中使.net缓存中的单个数据项无效

时间:2010-06-03 11:14:02

标签: asp.net vb.net caching

我有以下VB.NET代码在每个用户的基础上设置和读取缓存中的对象(即有点像会话)

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

我使用这些函数来保存我不想一直访问数据库的用户数据。但是,当数据更新时,我希望删除缓存的项目,以便再次创建它。

如何设置我设置的项目消失或将其设置为NOTHING或NULL?

1 个答案:

答案 0 :(得分:0)

将项目从缓存中取出就像调用HttpContext.Current.Cache.Remove(Key)一样简单,所以在您的情况下,您可能需要:

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

由于您说数据更新时您希望删除缓存项以便使用更新的数据重新缓存,您可能需要查看使用SqlCacheDependency对象。这会将缓存连接到数据库,以便在数据更改时,缓存的项目会自动更新以使其保持同步。