HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Memory cache implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationcachememory

Problem

I have created an open source memory cache called cachew and can be found here:
cachew. I would like your help to make it better.

Regarding the class Cache or its dependencies:

  • I am thinking of removing timeoutStyle and timeout from the Cache constructor and providing default values that can be changed via public properties. How do you like that?



  • How do you like my abstraction LockManager for ReaderWriterLockSlim?



  • Do you think my timer in Cache should be configurable? Through a property in cache, change internal to public or by another method?



  • Do you think it is a bad practice to start a timer in a constructor? If so, what would you do?



  • Would you consider the Cache threadsafe? Could it be better implemented?



```
public enum TimeoutStyle
{
FixedTimeout,
RenewTimoutOnQuery
}

public class Cache : ICache
{
private readonly ITimer expirationTimer;
private readonly IInternalCache internalCache;

private readonly LockManager lockManager = new LockManager();

public Cache(TimeoutStyle timeoutStyle, TimeSpan timeout) :
this(new InternalCache(timeoutStyle, timeout), new SystemTimer(5000))
{

}

internal Cache(IInternalCache iternalCache, ITimer expirationTimer)
{
if (iternalCache == null) throw new ArgumentNullException("iternalCache");
if (expirationTimer == null) throw new ArgumentNullException("expirationTimer");
this.internalCache = iternalCache;
this.expirationTimer = expirationTimer;

this.expirationTimer.Elapsed += ExpirationTimerElapsed;
this.expirationTimer.Start();
}

public object Get(CacheKey key, Func func)
{
using (lockManager.EnterRead())
{
object existingValue;
if (internalCache.TryGetValue(key, out existingValue))
return existingValue;
}

using (lockManager.EnterWrite())
{
object existingValue;
if (internalCache.TryGetVal

Solution

I am thinking of removing timeoutStyle and timeout from the Cache constructor and providing default values that can be changed via public properties. How do you like that?

Does it make sense to change these properties in the middle of using the cache? Is it a desirable feature? If yes, go ahead. If not, and you just want to provide default values to make it easier to construct the class, then add a default constructor that calls the existing one.

I don't know enough C# to comment on the rest, I hope you'll get good reviews!

Context

StackExchange Code Review Q#93937, answer score: 5

Revisions (0)

No revisions yet.