2

Is there any need to call

properties.Dispose();

at the end of an event receiver? Would this prevent memory leaks? Is this unnecessary? Is it best practice?

5

No, you don't need to dispose the properties, neither you need to dispose the SPWeb or SPSite object, returned using SPItemEventProperties.ListItem

Reason: The SPItemEventProperties class internally implements the Dispose() method itself.

How: Let's have a look at the source code of the SPItemEventproperties class using the Reflector, to make sure we are on the right track:

public sealed class SPItemEventProperties : SPEventPropertiesBase, IDisposable
{
    …

    private SPSite OpenSite()
    {
        if (((this.m_site == null) && (this.WebUrl != null)) && (this.m_site == null))
        {
            if (this.m_userToken == null)
            {
                this.m_site = new SPSite(this.WebUrl);
            }
            else
            {
                this.m_site = new SPSite(this.WebUrl, this.m_userToken);
            }
            this.m_siteCreatedByThis = true;
        }
        return this.m_site;
    }

    …

    public SPWeb OpenWeb()
    {
        this.OpenSite();
        if (this.m_site == null)
        {
            return null;
        }
        return this.m_site.OpenWeb(this.RelativeWebUrl);
    }

    …

    public void Dispose()
    {
        if (this.m_site != null)
        {
            while (this.m_siteCreatedByThis)
            {
                this.m_site.Dispose();
                this.m_site = null;
                this.m_siteCreatedByThis = false;
                break;
            }
        }
    }
}

Conclusion: So, you don't need to dispose the properties because the SPEventManager class makes sure to call Dispose() after the batch of event receivers have executed. You can also see Stefan's explanation on Technet MSDN for more details.^

You can also see some example event receivers examples on Technet for better guidance

0

The best practice for all .Net objects that implement IDisposable is to call .Dispose() when you are done with them. You can alternatively place them in a using () {} block and let the OS take care of the Dispose() for you.

The only exception to this rule is if you are using objects that you did not create. In SharePoint, these are typically objects passed into your code or existing objects such as those off of SPContext.Current.

  • Likewise, properties isn't created by the user and as such should not have Dispose called manually. – James Love Jul 7 '12 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.