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

Problem:

One of my collegue working on custom Web Part development and got this error “Trying to use an SPWeb object that has been closed or disposed and is no longer valid” It is very common amongst developers dealing with the SharePoint object model. Here is how the error looks like”

https://mysharepointsolution.files.wordpress.com/2012/03/spweb-dispose3.jpg

Reason:
It is a matter of Code. The reason behind this is a silly mistake that developers do, when trying to use the SPSite/SPWeb objects. Here is the bad code that resulted in the error:

https://mysharepointsolution.files.wordpress.com/2012/03/spweb-dispose1.jpg

Solution:

In above code snippet, developer used “using” clause alongwith the SPContext.Current.Site which resulted in this error. It implicilty disposes the SPSite object which should not be done when using the SPContext object. Which is not ideal to use. Lets rectify the code a little bit and have a look at the good code snippet which resolved this issue:

https://mysharepointsolution.files.wordpress.com/2012/03/spweb-dispose2.jpg

Noteworthy:
After removing the “using” clause from the SPContext.Current.Site code works fine!
Same thing applies when try to dispose either explicitly/implicitly the SPContext.Current.Web object.
So, NEVER dispose SPContext objects either implicitly pulling the “using” clause or explicitly by “using” Dispose method from “Finally” block.

7 comments

  1. Howdy would you mind letting me know which
    hosting company you’re utilizing? I’ve loaded your blog in 3 different
    internet browsers and I must say this blog loads a lot quicker then most.
    Can you recommend a good hosting provider at a reasonable price?
    Thanks, I appreciate it!

    Feel free to surf to my webpage; website developers near me

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s