I have created a generic CachedRepository
that looks like the following:
public class CachedRepository<T> : ICachedRepository, IRepository<T> where T : BaseModel, new()
{
private static readonly Lock<T> TypeLock = new Lock<T>();
public void DeleteBatch(IQueryable<T> entities)
{
lock (TypeLock)
{
// delete logic here
}
}
public T GetNoTracking(int id)
{
lock (TypeLock)
{
// fetch by id logic here
}
}
}
By using a generic object to lock on, I will obtain locking per type (i.e. threads working with different types will not wait one after the other). However, this class is used for lists of objects that are rarely changed, but heavily read, so using simple locking with lock
will delay a reader until another reader is done.
I had a look upon ReaderWriterLockSlim, but it is not a generic class and if I use it I lose the type locking I have now.
Question: How can I reduce locking for readers while keeping the type locking that lock(generic_type_instance)
pattern is providing?