(Lviv community of .NET developers)

Cache results with duration

January 18, 2008 15:15 by alexk
This time I want to show how to implement simple cache with duration interval. For it implementation were used generics and anonymous delegate C# features. Class is very simple but power that it give us is unmeasurable.
In real life this class is designed for DB oriented applications. It allowiing to cache long time taken operations results of which has long time of life. Enjoy.


Class declaration:

  internal class CacheWithDuration<T> where T : class
  {
    public delegate T GetValueEventHandler();

    private T m_data;
    private DateTime m_last = DateTime.MinValue;
    private int m_duration;
    private CacheWithDuration<T>.GetValueEventHandler m_delegate;

    public T Data
    {
      get
      {
        DateTime now = DateTime.Now;

        if( m_duration < now.Subtract( m_last ).TotalSeconds )
        {
          m_data = m_delegate();
          m_last = now;
        }
        else
        {
          _tracer.Info( "Cache hit." );
        }

        return m_data;
      }
    }

    public CacheWithDuration( int duration, CacheWithDuration<T>.GetValueEventHandler @delegate )
    {
      m_duration = duration;
      m_delegate = @delegate;
    }
  }


Example of usage:

/// <summary>Cache all projects results for 1 second</summary>
private CacheWithDuration<DataView> m_cacheAllProjects;

public override DataView GetAllProjects()
{
  _tracer.Verbose( "GetAllProject", "DatabaseRemote::method call" );

  if( m_cacheAllProjects == null )
  {
    m_cacheAllProjects = new CacheWithDuration<DataView>( 1, delegate()
      {
        lock( this.SyncObject )
        {
          sqlProjects.Fill( this.Data.Projects );
          return base.GetAllProjects();
        }
      }
    );
  }

  return m_cacheAllProjects.Data;
}

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

July 7. 2010 15:40

Must disagree with the comment above, get your details straight prior to writting such a comment.

Peeing

July 8. 2010 02:44

I totally agree.

Charlie

July 13. 2010 09:29

Just don't give up trying to do what you really want to do. Where there is love and inspiration, I don't think you can go wrong.

no credit check loans

Add comment


(Will show your Gravatar icon)