Hendrik Bulens All about .NET development

Managing shared information with IDisposable in C# and SharePoint

Every once in a while you’ll have a situation in which you temporarily have to use different (shared) settings and reset them if all work is done. An example of this is often seen in SharePoint, for instance disabling events when updating items in event receivers, or allowing unsafe updates. A workaround that I have seen a lot is that developers add a TRY/CATCH/FINAL block for each method they want to reset some objects. In this post, I’ll talk about an alternative way of achieving this behavior by the implementation if the IDisposable interface.

For many SharePoint developers, these two code excerpts will look quite familiar:

In many scenarios this coding pattern will be just fine because there is need of exception handling, but to some extent it isn’t exactly the best way. Instead, you could achieve the same kind of behavior by implementing the IDisposable interface. Here’s an interesting utility for SharePoint:

All code within the using statement of the DisabledItemEventsScope object will be executed without the change of triggering new events. As soon as the object is disposed, the EventFiringEnabled property is set to its original state. There are examples too where you could use this pattern:

Here’s how you use this class:

All code within the curly brackets will use the settings that are specified in the using statement. In this case, the Console window will output the text with a yellow foreground color. After the scope object is disposed, it will reset the console window colors to its original settings. I’m not saying this approach is the best but it certainly is a worthy alternative that you should consider when you’re in this kind of situation of shared data.

Add comment

Leave a Reply

Hendrik Bulens All about .NET development