Exception Trying to use an SPWeb object that has been closed or disposed and is no longer valid.


 

Have seen many developers struggling with this exception and its a common mistake that people make in their code.

SPWeb, SPSite objects leak memory if they are not disposed properly.  The problem is so much talked about that as soon as we think of SPSite and SPWeb we unconsciously put

using (SPWeb spweb = blah blah)

However when you use SPContext to get site or web object you should not be using “USING” or you should not dispose that object.  SPContext is passed to another web part on the page and SharePoint will dispose it when done.

Hence if you have been using (SPSite spsite = SPContext.Current.Site) it is wrong.  It might not always break as you might just have one web part in your code but you will see it break as soon as you add another web part and may be try to check in the page.

so change

using (SPSite spsite = SPContext.Current.Site)

to

SPSite site = SPContext.Current.Site.


Comments (3)

  1. Eric says:

    Thanks It was very helpful have been struggling and was lucky to find this post and even luckier coz it looks like you just posted it

  2. Anonymous says:

    Thank you!  This was really helpful!

  3. Dimi says:

    Thank you!  This was really great explanation

Skip to main content