I'm using a static cache on a service and I found a problem of concurrence in NHibernate Session when the key was missing and was forced to get from database (using Evict).
I wrote a lock sentence on the code (an abstraction below) to solve the problem, but i can't understand that the lock was not working. Finally I put readonly on the static "lock" variable and worked, but I can't understand why not working when the assign of the static variable was only on top of the class, how it works?
private static object lockCacheElement = new object()
....
public static T ManageCacheElement<T>(int objectId, string key, Func<T> findById) {
lock (lockCacheElement)
{
Log.DebugFormat("ManageCacheElement({0}): START", key);
if (TryGetDataElement<T>(key, out result))
{
Log.DebugFormat("ManageCacheElement({0}): END1 ", key);
return result;
}
else
{
result = findById(objectId, true);
SetDataElement(key, result);
Log.DebugFormat("ManageCacheElement({0}): END2 ", key);
return result;
}
}
}
That code traces something like that:
{DEBUG} 28/11 17:37:01.0423 [67] - ManageCacheElement(xxx): START
{DEBUG} 28/11 17:37:01.0423 [72] - ManageCacheElement(xxx): START
{DEBUG} 28/11 17:37:01.0423 [72] - ManageCacheElement(xxx): END1
{DEBUG} 28/11 17:37:01.0423 [92] - ManageCacheElement(xxx): START
{DEBUG} 28/11 17:37:01.0423 [92] - ManageCacheElement(xxx): END1
{DEBUG} 28/11 17:37:01.0580 [96] - ManageCacheElement(xxx): START
{DEBUG} 28/11 17:37:01.0580 [96] - ManageCacheElement(xxx): END1
{DEBUG} 28/11 17:37:01.0580 [10] - ManageCacheElement(xxx): START
And if I set the readonly modifier on lockCacheElement.
private static readonly object lockCacheElement = new object()
It works fine, but I can't understand why?