This is one of the most important articles I have read lately:
Best Practices for writing web parts in SharePoint(Compiled from various blogs and articles)
- The link below describes in more detail the practice elaborated in this point
Using Disposable Windows SharePoint Services Objects
What it explains is that when you develop web parts and use the sharepoint objects (like spsite and spweb) you have to dispose of them because the garbage collector wont.
The article also contains code examples for the recommended three ways to do this:
1. use "dispose"
2. use "using"
3. use "try, catch, and finally blocks"
Example for using "using":
String str;
using(SPSite oSPsite = new SPSite("http://server"))
{
using(SPWeb oSPWeb = oSPSite.OpenWeb())
{
str = oSPWeb.Title;
str = oSPWeb.Url;
}
}
Example for using "try, catch, and finally blocks":
String str;
SPSite oSPSite = null;
SPWeb oSPWeb = null;
try
{
oSPSite = new SPSite("http://server");
oSPWeb = oSPSite.OpenWeb(..);
str = oSPWeb.Title;
}
catch(Exception e)
{
}
finally
{
if (oSPWeb != null)
oSPWeb.Dispose();
if (oSPSite != null)
oSPSite.Dispose();
}
No comments:
Post a Comment