Mar 10, 2010

SharePoint Disposing Myth: You have to dispose SPWeb explicitly!?

It seems to me that every post, article and book tells you to explicitly dispose every SPWeb (excepts them coming from SPContext). But is that right?
Not quite! Every SPSite tracks the SPWebs that it has emitted. A internal list named “m_openedWebs” holds these references. It doesn’t matter from which member of the SPSite you will get the SPWeb (RootWeb, OpenWeb, AllWebs, Add) the SPSite holds a reference on it. When you dispose the SPSite it loops through all SPWebs in “m_openedWebs” and calls the Close method on each. The dispose method of SPWeb does nothing else than calling it’s close method. Means when you dispose a SPSite, all SPWebs that it has emitted will be disposed implicitly! A construct like this
using(SPSite site = new SPSite("http://server/site"))
{
     using(SPWeb web = site.OpenWeb())
     {
       //...
     }
}
is not necessary, because the using for the SPSite will implicitly dispose all of it SPWebs. By the way if you call the dispose method of the SPWeb explicitly it will internally remove itself from the “m_openedWebs” list. Sure there are scenarios where explicitly disposing of SPWebs is important, for example when you loop through the AllWebs property of the SPSite with maybe hundreds of SPWebs. Because every SPWeb consumes a lot of memory! On the other hand you don’t have to be afraid when you pass a SPWeb reference across your API. When you finally dispose the SPSite, all SPWebs it has emitted will be disposed too and you will not cause a memory leak. I think the SharePoint team have implemented this pretty well.

When you create an instance of SPSite you are responsible to dispose it. When to dispose SPWeb that have been emitted by your SPSite depends on the scenario.


What could cause problems indeed is when you still use a SPWeb that has already been disposed, doesn’t matter if it has been disposed implicitly or explicitly. The SPWeb will be reopened but will not be listed in the “m_openedWebs” of the SPSite. Means it can not be implicitly disposed by the SPSite anymore. A better and approach would have been to throw an ObjectDisposedException on all members after the SPWeb has been disposed.

You don’t believe? Just take a look at the following snippet or even better let it run:
Console.WriteLine("Create a SPSite");
SPSite site = new SPSite("http://localhost:101");

Console.WriteLine("Open 5 SPWebs...");
SPWeb web1 = site.RootWeb;
SPWeb web2 = site.OpenWeb();
SPWeb web3 = site.OpenWeb("my");
SPWeb web4 = site.AllWebs[1];
SPWeb web5 = site.AllWebs.Add(Guid.NewGuid().ToString());

int openedWebs = (typeof(SPSite).InvokeMember("m_openedWebs",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
null, site, null) as ICollection).Count;      

Console.WriteLine("Acutally opened SPWebs: " + openedWebs.ToString());

Console.WriteLine("Dispose web1 explicitly");
web1.Dispose();

openedWebs = (typeof(SPSite).InvokeMember("m_openedWebs",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
null, site, null) as ICollection).Count;     

Console.WriteLine("Dispose the SPSite");         
site.Dispose();

openedWebs = (typeof(SPSite).InvokeMember("m_openedWebs",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
null, site, null) as ICollection).Count;

Console.WriteLine("Acutally opened SPWebs: " + openedWebs.ToString());

Console.ReadKey();   


Any feedback?

17 comments:

Torsten said...

Schöne Erklärung.

Der Dispose Checker ist aber anderer Meinung. Ok das ist er ja meistens :)

SharePoint.BestPractices : In method ... Dispose was not called on fileWeb

Christian said...

I suppose the Dispose Checker is wrong! Check out the SPSite with .NET Reflector.

Torsten said...

I know. The Dispose Checker isn't always right. Perhaps we should tell them to change their check routines.

Anonymous said...

If you have about 100 sub sites, you will see why disposing inside the for loop is necessary. The best practice is that we should keep them in the memory as short as possible.

Christian said...

Hello, that's right for this scenario!

Anonymous said...

wieso sollte man eine 100 prozent lösung (dispose aufrufen) nicht einfach verwenden??

sehe da keinen nachteil und im gegenzug keinen vorteil dispose nicht aufzurufen...

what is a digital signature said...

Nice post! Provides some good info for people evaluating different approaches. Thanks for sharing.

Chanel Handbags 2015 said...

I can’t wait for February actually, because I have been waiting for the restocking of Mansur Gavriel bucket bags– the bucket bag is one of the hottest styles at the moment, and it’s funny because this style came back to haunt many of us from a decade or so ago

Chanel Handbag 2015 said...

I’m currently in Shangrila Boracay for the MAC Cosmetics Spring/ Summer 2015 trend report- presentation and was about to blog a bit about my stay when the photo of Dakota Johnson carrying the Chanel Boy with tone-on-tone logo caught my eye.

Hug Day said...

happy hug day 2016 SMS
hug day 2016 Wishes cards greetings
Hug day Date 2016
hug day sms

风骚达哥 said...

20160423 junda
air jordans
cheap oakley sunglasses
kate spade outlet
adidas stan smith
ray ban sunglasses
michael kors outlet
nike air max shoes
cheap omega watches
yeezy boost 350
michael kors outlet online
michael kors outlet online
nike free runs
air jordan uk
michael kors outlet online
pandora charms
ray ban outlet
calvin klein outlet
fitflops sale clearance
toms outlet
nike huarache white
sac longchamp
toms outlet
michael kors outlet clearance
bottega veneta outlet
armani watches
gucci handbags
nike blazer
oakley sunglasses
true religion jeans
cheap jordans
ray bans
hollister
bottega veneta handbags
jimmy choo outlet
oakley sunglasses
converse
prada outlet
reebok shoes
true religion
burberry outlet

Libin Huang said...

20160426libinhollister clothing store
oakley sunglasses
michael kors handbags
tiffany outlet
ray-ban sunglasses
gucci outlet online
ray-ban sunglasses
burberry outlet online
coach outlet canada
ray-ban sunglasses
herve leger outlet
ray ban sunglasses sale
air max 90
oakley sunglasses
adidas wings shoes
michael kors outlet
michael kors factory outlet
louis vuitton bags
michael kors online outlet
nba jerseys
ralph lauren pas cher
oakley sunglasses
toms shoes
nike air max 90
nike tn pas cher
air max 90
lululemon outlet
nike air force 1
true religion outlet
michael kors outlet
burberry outlet store
ray ban sunglasses
kobe shoes
true religion outlet
discount michael kors handbags

Yuanyuan Lin said...

7.14llllllyuan"timberland shoes"
"soccer jerseys wholesale"
"longchamp pliage"
"cheap oakley sunglasses"
"true religion jeans"
"louis vuitton pas cher"
"rolex orologi"
"christian louboutin shoes"
"michael kors clearance"
"cheap nba jerseys"
"oakley sunglasses wholesale"
"tory burch shoes"
"tory burch outlet"
"chicago blackhawks jerseys"
"longchamp outlet"
"omega watches"
"adidas trainers"
"cheap nike shoes"
"nike outlet store online"
"michael kors outlet clearance"
"michael kors uk"
"montblanc pens"
"michael kors canada"
"longchamp handbags"
"ray ban sunglasses"
"abercrombie and fitch"
"mcm outlet"
"puma shoes"
"ralph lauren uk"
"nike air max 90"
"rolex watches,rolex watches,swiss watches,watches for men,watches for women,omega watches,replica watches,rolex watches for sale,rolex replica,rolex watch,cartier watches,rolex submariner,fake rolex,rolex replica watches,replica rolex"
"mulberry outlet"
"air max 90"
"ferragamo outlet"
"christian louboutin outlet"
7.14

aboshady said...

شركة شراء اثاث مستعمل بالرياض
ارقام اثاث مستعمل بالرياض
محلات شراء الاثاث المستعمل بالرياض
محلات الاثاث المستعمل بالرياض

Mohamed Shokry said...

شراء اثاث مستعمل بالرياض
شراء الاثاث المستعمل بالرياض
محلات شراء الاثاث المستعمل بالرياض
ارقام الاثاث المستعمل بالرياض
حقين الاثاث المستعمل بالرياض
شراء اثاث مستعمل
شركة مكافحة حشرات بجدة
مكافحة حشرات بجدة
شراء الاثاث المستعمل بجدة ومكة

Fangyaya said...

michael kors handbags
coach factory outlet online
ghd flat iron
louis vuitton handbags
ralph lauren
polo shirts
ray ban sonnenbrille
nfl jerseys wholesale
kate spade outlet
ray ban sunglasses
coach outlet online
coach outlet online
louis vuitton outlet stores
christian louboutin sale
giuseppe zanotti sneakers
cheap ray ban sunglasses
michael kors outlet clearance
louboutin shoes
air jordan shoes
tods sale
replica rolex watches
coach outlet
coach outlet store online
louis vuitton outlet stores
coach outlet store online clearances
adidas yeezy
tory burch flats
polo ralph lauren
coach outlet store online clearances
air jordan 11
20168.8chenjinyan

mohamed gamal said...

شراء اثاث مستعمل بالرياض
شراء الاثاث المستعمل بالرياض
محلات شراء الاثاث المستعمل بالرياض
ارقام الاثاث المستعمل بالرياض
حقين الاثاث المستعمل بالرياض
شراء اثاث مستعمل
شركة مكافحة حشرات بجدة
مكافحة حشرات بجدة
شراء الاثاث المستعمل بجدة ومكة