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