Need help profiling .NET caching extension method.

Posted by rockinthesixstring on Stack Overflow See other posts from Stack Overflow or by rockinthesixstring
Published on 2011-01-03T18:30:58Z Indexed on 2011/01/03 19:54 UTC
Read the original article Hit count: 190

Filed under:
|

I've got the following extension

Public Module CacheExtensions
    Sub New()
    End Sub

    Private sync As New Object()
    Public Const DefaultCacheExpiration As Integer = 1200 ''# 20 minutes

    <Extension()> 
    Public Function GetOrStore(Of T)(ByVal cache As Cache, ByVal key As String, ByVal generator As Func(Of T)) As T
        Return cache.GetOrStore(key, If(generator IsNot Nothing, generator(), Nothing), DefaultCacheExpiration)
    End Function

    <Extension()> 
    Public Function GetOrStore(Of T)(ByVal cache As Cache, ByVal key As String, ByVal generator As Func(Of T), ByVal expireInSeconds As Double) As T
        Return cache.GetOrStore(key, If(generator IsNot Nothing, generator(), Nothing), expireInSeconds)
    End Function

    <Extension()> 
    Public Function GetOrStore(Of T)(ByVal cache As Cache, ByVal key As String, ByVal obj As T) As T
        Return cache.GetOrStore(key, obj, DefaultCacheExpiration)
    End Function

    <Extension()> 
    Public Function GetOrStore(Of T)(ByVal cache As Cache, ByVal key As String, ByVal obj As T, ByVal expireInSeconds As Double) As T
        Dim result = cache(key)

        If result Is Nothing Then

            SyncLock sync
                If result Is Nothing Then
                    result = If(obj IsNot Nothing, obj, Nothing)
                    cache.Insert(key, result, Nothing, DateTime.Now.AddSeconds(expireInSeconds), cache.NoSlidingExpiration)
                End If
            End SyncLock
        End If

        Return DirectCast(result, T)

    End Function

End Module

From here, I'm using the extension is a TagService to get a list of tags

    Public Function GetTagNames() As List(Of String) Implements Domain.ITagService.GetTags
        ''# We're not using a dynamic Cache key because the list of TagNames
        ''# will persist across all users in all regions.
        Return HttpRuntime.Cache.GetOrStore(Of List(Of String))("TagNamesOnly",
                                                                Function() _TagRepository.Read().Select(Function(t) t.Name).OrderBy(Function(t) t).ToList())
    End Function

All of this is pretty much straight forward except when I put a breakpoint on _TagRepository.Read(). The problem is that it is getting called on every request, when I thought that it is only to be called when Result Is Nothing

Am I missing something here?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about caching