在C#上使用Cache(包括VB代码)

时间:2009-03-10 09:20:28

标签: c# asp.net

如何以与以下VB代码类似的方式使用Web服务器缓存:

   ////  FindData() returns real data
   //// FindCached() returns from cache (kept 20 minute)

    Protected Function RegisterCachedData(ByVal id As String) As Integer
        Dim onCacheRemove As CacheItemRemovedCallback
        onCacheRemove = New CacheItemRemovedCallback(AddressOf Me.CheckCallback)
        Cache.Insert("AverageData", FindData(1), Nothing, DateTime.Now.AddMinutes(20), TimeSpan.Zero, 1, onCacheRemove)
    End Function

    Sub CheckCallback(ByVal str As String, ByVal obj As Object, ByVal reason As CacheItemRemovedReason)
        RegisterCachedData(0)
    End Sub

   Protected Function FindCached() As Integer
        If Cache.Get("AverageData") Is Nothing Then RegisterCachedData(0)
        Return Cache.Get("AverageData")
    End Function

2 个答案:

答案 0 :(得分:2)

Asp.Net是Asp.Net,无论您使用何种语言。用VB.Net可以做的也可以用C#完成。

答案 1 :(得分:2)

同样的道理。这应该这样做:

protected int RegisterCachedData(string id) {
   CacheItemRemovedCallback onCacheRemove;
   onCacheRemove = new CacheItemRemovedCallback(CheckCallback);
   Cache.Insert("AverageData", FindData(1), null, DateTime.Now.AddMinutes(20), TimeSpan.Zero, 1, onCacheRemove);
}

void CheckCallback(string str, object obj, CacheItemRemovedReason reason) {
   RegisterCachedData("0");
}

protected int FindCached() {
   if (Cache.Get("AverageData") == null) RegisterCachedData("0");
   return Cache.Get("AverageData");
}