You can employ certain coding techniques to ensure object disposal. These techniques include using the following in your code:
- Dispose method
- using clause
- try, catch, and finally blocks
String str; using(SPSite oSPsite = new SPSite("http://server")) { using(SPWeb oSPWeb = oSPSite.OpenWeb()) { str = oSPWeb.Title; str = oSPWeb.Url; } }
//using try/catch/finally
String str; SPSite oSPSite = null; SPWeb oSPWeb = null; try { oSPSite = new SPSite("http://server"); oSPWeb = oSPSite.OpenWeb(..); str = oSPWeb.Title; } catch(Exception e) { //Handle exception, log exception, etc. } finally { if (oSPWeb != null) oSPWeb.Dispose(); if (oSPSite != null) oSPSite.Dispose(); }
//using dispose method
public static void SPSiteCollectionForEachBestPractice() { string sUrl = "http://spvm"; using (SPSite siteCollectionOuter = new SPSite(sUrl)) { SPWebApplication webApp = siteCollectionOuter.WebApplication; SPSiteCollection siteCollections = webApp.Sites; SPSite siteCollectionInner = null; foreach (siteCollectionInner in siteCollections) { try //Should be first statement after foreach. { Console.WriteLine(siteCollectionInner.Url); //Exception occurs here. } finally { if(siteCollectionInner != null) siteCollectionInner.Dispose(); } } } } // SPSite object siteCollectionOuter.Dispose() automatically called. }
No comments:
Post a Comment
Thank you for Commenting Will reply soon ......