Disable ItemUpdated Endless loop in Event Receiver

In one of my project, I had a requirement to build an event receiver which is for item updated.

The logic is when I update the document, programmatically my custom field will be updated with a value.

So I thought of adding event receiver for that and wrote below code:

public override void ItemUpdated(SPItemEventProperties properties)
{
    base.ItemUpdated(properties);
    SPListItem listItem = properties.ListItem;
    listItem["MyCustomField"] = "Okay, I’m updated!";
    listItem.Update();
}

When I ran this code with debugging,

listItem.Update();

fired and event receiver called again as item is being updated so my break-point started over from

base.ItemUpdated(properties);

It means again ItemUpdated event receiver will be called.

So this was like endless loop. There must be some workaround for this which is as follow: we need to write updating code in a way that it doesn’t trigger event receiver again.

So I have created below DisabledEventsScope class in the event receiver file.

class  DisabledEventsScope : SPItemEventReceiver, IDisposable
{
    // Boolean to hold the original value of the EventFiringEnabled property
    bool _originalValue;
    public DisabledEventsScope()
    {
        // Save off the original value of EventFiringEnabled
        _originalValue = base.EventFiringEnabled;

        // Set EventFiringEnabled to false to disable it
        base.EventFiringEnabled = false ;
    }
    public void Dispose()
    {
        // Set EventFiringEnabled back to its original value
        base.EventFiringEnabled = _originalValue;
    }
}

This class will turn off the firing of the event receiver by setting Boolean value of event receiver, run the code without endless loop. We need to implement this class in our code so that it disable event firing.

public override void ItemUpdated(SPItemEventProperties  properties)
{
    base.ItemUpdated(properties);
    using (DisabledEventsScope scope = new DisabledEventsScope ())
    {
        SPListItem listItem = properties.ListItem;
        listItem["MyCustomField"] = "Okay, I’m updated!";
        listItem.Update();
    }
}

Once this code is running, it won’t be firing endless loop of event receiver.

Happy SharePointing.!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s