Expand Minimize

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.

CheckId SPC050235
TypeName ApplyLockForCachingObjects
Severity CriticalWarning
Type Assembly

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, ..);
  }
}

To suppress this violation in managed code add the following attribute to the method which contains the instruction (available since SPCAF version v5.2). Learn more about SuppressMessage here.

// Important: Ensure to have #define CODE_ANALYSIS at the beginning of your .cs file
[SuppressMessage("SPCAF.Rules.BestPracticesGroup", "SPC050235:ApplyLockForCachingObjects", Justification = "Provide reason for suppression here")]
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.