Race Condition in SharePoint 2010

Background

On the other day I have been told write a code on event handler to update fields value based on condition. I thought it would be very simple, but it was not. Though the implementation was very simple with Visual Studio 2010 🙂

Problem

As the title tells the story, but let me elaborate more. I have given a task that set the field value based on certain condition when ever item is updated or added. So I have open Visual Studio 2010 -> Added Event Listener -> Changed the code as per the requirement in ItemAdded event.

try
{
	SPListItem _currentItem = properties.ListItem;
	if (_currentItem != null)
	{
		if (_currentItem["Field"].ToString() == "True")
		{
			_currentItem["OtherField"] = "Closed";
		}
		else if (_currentItem["Field"].ToString() == "False")
		{
			_currentItem["OtherField"] = "Open";
		}
		_currentItem.Update();
		_currentItem.SystemUpdate(false);
	}
}
catch (Exception ex)
{ }

Deployed the same and was debugging. The problem was, when I was debugging this event was firing again and again. And I was getting following error.

Save Conflict.

Your changes conflict with those made concurrently by another user. If you want your changes to be applied, click Back in your Web browser, refresh the page, and resubmit your changes.

Reason

When you use SPListItem’s “update()” method to update the SPListItem it trigger the so many activities and all procedures goes into the recursive loop. So your event handlers fired again and the it tries to save already saved item. And you get above error 🙁

Solution

In order to solve this problem we just have add two lines of code, one before and one after 🙂

StopEventFiring();
try
{
	SPListItem _currentItem = properties.ListItem;
	if (_currentItem != null)
	{
		if (_currentItem["Field"].ToString() == "True")
		{
			_currentItem["OtherField"] = "Closed";
		}
		else if (_currentItem["Field"].ToString() == "False")
		{
			_currentItem["OtherField"] = "Open";
		}
		_currentItem.Update();
		_currentItem.SystemUpdate(false);
	}
}
catch (Exception ex)
{ }
StartEventFiring();

And you add these two methods which changes the EventFiringEnabled property to its appropriate value

/// <summary>
/// Enable event firing
/// </summary>
public void StartEventFiring()
{
	EventFiringEnabled = true;
}

/// <summary>
/// Disable event firing
/// </summary>
public void StopEventFiring()
{
	EventFiringEnabled = false;
}

And last but not the list you also add Synchronous property in Elements.xml file

<Receiver>
	<Name>UpdateListItemAdded</Name>
	<Type>ItemAdded</Type>
	<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
	<Class>SPDemo.UpdateList.UpdateList</Class>
	<SequenceNumber>10000</SequenceNumber>
	<Synchronization>Synchronous</Synchronization>
</Receiver>

And that’s it, Happy SharePointing 🙂

Tagged with: , ,