SPC050235: Apply lock when caching SharePoint objects

Some SharePoint objects are not thread safe and caching can cause applications to fail and cause unexpected or unrelated user errors. To avoid this ensure locking of cached objects.

TypeName: ApplyLockForCachingObjects
CheckId: SPC050235
Severity: CriticalWarning
Type: AssemblyFileReference
Resolution

Follow the instructions for locking the cache as described in 'Object Caching Techniques' (see link).

Bad Practice:

public void CacheData()
{
  SPListItemCollection oListItems = DoQueryToReturnItems();
  cache.Add("ListItemCacheName", oListItems, ..);
}
Good Practice
private static object _lock =  new object();

public void CacheData()
{
  SPListItemCollection oListItems = DoQueryToReturnItems();  
  lock(_lock)  
  {
    cache.Add("ListItemCacheName", oListItems, ..);
  }
}

Links

comments powered by Disqus