I am using code similar to the following to apply an update to an SPListItem, after necessarily elevating to System privileges on said item.
Because this can be called multiple times for the same item, possibly concurrently, I have a lock
from opening the item to updating it. This means concurrent updates do not cause a save conflict, but wait for the previous update to finish.
private static string lockMe = "lockMe";
public static void AffectListItem(SPListItem listItem)
{
// Elevate
using (SPSite site = new SPSite(listItem.Web.Site.ID, SPUserToken.SystemAccount))
{
using (SPWeb web = site.OpenWeb(listItem.Web.ID))
{
SPList list = web.Lists[listItem.ParentList.ID];
lock(something) // lockMe or listItem, see below
{
SPListItem cleanItem = list.GetItemById(listItem.ID);
// Perform a small server-side update.
MakeChanges(cleanItem);
cleanItem.Update();
}
}
}
}
However, I'm not sure exactly what I should be locking on. If I lock on a private, static variable of the class containing this method, then I lock when any items are updated concurrently, not just when the same item is updated twice concurrently. If I lock on listItem
, I get no lock at all, because the different listItem
s are different objects.
Is there something I can lock
against that will provide this per-ListItem locking that I need? Alternatively, is this a bad idea, or is there a totally different method of going about it?