SPWeb/SPSite.Dispose()
By now most of you should know that there is a SharePoint Diagnostics Tool. This really is a great tool, since it scans your assemblies for memory leaks.
You should also know, that there is an occasion you can create a memory leak which the tool will not recognize.
1: using (var site = new SPSite(“http://yoururl”))
<span class=lnum> 2: </span>{
3: SPWeb web = null;
<span class=lnum> 4: </span> <span class=kwrd>try</span>
5: {
<span class=lnum> 6: </span> web = site.OpenWeb();
7: // do something with this web
<span class=lnum> 8: </span> <span class=rem>// ...</span>
9: // done. don't need it anymore. but i need another web
<span class=lnum> 10: </span> web = site.AllWebs[<span class=str>"webname"</span>];
11: }
<span class=lnum> 12: </span> <span class=kwrd>finally</span>
13: {
<span class=lnum> 14: </span> <span class=kwrd>if</span> (web != <span class=kwrd>null</span>) web.Dispose();
15: }
<span class=lnum> 16: </span>}
The SPWeb from line 6 will not be disposed in line 14, because in line 10 we assign another SPWeb to the web!
So what do we do?
Just dispose the web manually, before we assign a new SPWeb to it. You can use two usings around the webs, or dispose it via web.Dispose(). That’s it.