Tuesday, April 23, 2013

When to use ‘using’ and ‘dispose’ and when not to use in SharePoint


If you create your own SPSite object, you can use the Dispose method to close the object. However, if you have a reference to a shared resource, such as when the object is provided by the GetContextSite method in a Web Part, do not use either method to close the object. Using either method on a shared resource causes an Access Violation error to occur
Likewise, If you obtain an SPWeb object using OpenWeb or RootWeb, the best practice is to implement the using statement or the Dispose method to dispose of the object.
However, if you have a reference to a shared resource, such as when you obtain the Web site object from the SPContext object in a Web Part by using SPContext.Current.Web, do not use either method to close the object.

No comments:

Post a Comment