Click to Rate and Give Feedback
MSDN
MSDN Library
Web Development
Technical Articles
 Best Practices: Using Disposable Wi...

  Switch on low bandwidth view
Community Content
In this section
Statistics Annotations (0)
Best Practices: Using Disposable Windows SharePoint Services Objects

Summary: Learn best practices to follow when using Windows SharePoint Services objects to avoid retaining the objects in memory in the Microsoft .NET Framework. (29 printed pages)

Scott Harris, Microsoft Corporation

Mike Ammerlaan, Microsoft Corporation

Roger Lamb, Microsoft Corporation

Stefan Goßner, Microsoft Corporation

Published: June 2006

Updated: January 2009

Applies to: Windows SharePoint Services 3.0, Windows SharePoint Services 2.0, Microsoft Office SharePoint Server 2007, Microsoft Office SharePoint Portal Server 2003

Contents

Related download: SharePoint Dispose Checker Tool

Introduction to Using Disposable Windows SharePoint Services Objects

The objects in the Windows SharePoint Services 3.0 object model serve as an interface for working with Windows SharePoint Services data. Frequently, developers call into the object model to read data from or write new data to the Windows SharePoint Services store.

The Windows SharePoint Services object model contains objects that implement the IDisposable interface. You must take precautions when using these objects to avoid their long-term retention in memory in the Microsoft .NET Framework.

Specifically, you should explicitly dispose of those SharePoint objects that implement IDisposable when you are finished using them.

In scenarios in which you use SharePoint objects extensively—for example, in SharePoint sites that use custom Web Parts—you can cause the following unusual behaviors by not disposing of SharePoint objects when you are finished with them.

  • Frequent recycles of the Windows SharePoint Services application pool, especially during peak usage

  • Application crashes that appear as heap corruption in the debugger

  • High memory use for Microsoft Internet Information Services (IIS) worker processes

  • Poor system and application performance

This article serves as a guide to the proper procedures for handling and disposing of SharePoint objects that implement IDispose. The issues discussed in this article are also flagged by the SharePoint Dispose Checker Tool, a free program available as a download that inspects your assemblies for coding practices that cause memory leaks because of improper handling and disposal of SharePoint objects.

Why Dispose?

Several of the Windows SharePoint Services objects, primarily the SPSite class and SPWeb class objects, are created as managed objects. However, these objects use unmanaged code and memory to perform the majority of their work. The managed part of the object is much smaller than the unmanaged part. Because the smaller managed part does not put memory pressure on the garbage collector, the garbage collector does not release the object from memory in a timely manner. The object's use of a large amount of unmanaged memory can cause some of the unusual behaviors described earlier. Calling applications that work with IDisposable objects in Windows SharePoint Services must dispose of the objects when the applications finish using them. You should not rely on the garbage collector to release them from memory automatically.

Finding Incorrectly Disposed Objects

You can identify the potential presence of incorrectly disposed objects by asking the following questions:

  1. Does your application pool recycle frequently, especially under heavy loads (assuming that the application pool is set to recycle when a memory threshold is reached)?

    The memory threshold should be 800 MB–1.5 GB (assuming at least 2 GB of RAM). Setting the recycle of the application pool to occur closer to 1 GB gives the best results, but experiment to determine what settings work best for your environment. If the recycle setting is too low, you experience performance issues because of frequent application pool recycles. If the setting is too high, your system experiences performance problems because of page swapping, memory fragmentation, and other issues.

  2. Does your system perform poorly, especially under heavy loads?

    As memory usage begins to increase, the system must compensate, for example, by paging memory and handling memory fragmentation.

  3. Does your system crash or do users experience unexpected errors such as timeouts or page-not-available errors, especially under heavy loads?

    Again, when memory usage increases or gets fragmented, some functions fail because they cannot allocate memory for other operations. In many cases, the code does not properly handle the "out of memory" exception, which leads to false or misleading errors.

  4. Does your system use custom or third-party Web Parts or custom applications?

    You might not be aware that they must dispose of SharePoint objects and why, assuming that garbage collection performs this function automatically. However, that is not true in all cases.

If you answer "yes" to number 4, and to one or more of the other questions, there is a good chance that your custom code is not disposing of items properly.

If your sites are displaying any of the unusual behaviors described previously, you can determine whether the cause is a memory leak due to incorrectly disposed objects by checking the ULS logs (available at C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\LOGS) for entries related to the SPRequest object. Each instance of SPSite and SPWeb contains a reference to an SPRequest object that, in turn, contains a reference to an unmanaged COM object that handles communications with the database server. Windows SharePoint Services monitors the number of SPRequest objects that exist in each specific thread and in parallel threads, and adds useful entries to the logs under the three following scenarios:

  • The total number of SPRequest objects exceeds a configurable threshold.

  • An SPRequest object continues to exist at the end of a thread.

  • An SPRequest object was garbage collected.

The first scenario occurs most frequently, especially if your site uses the default threshold value of eight SPRequest objects. Whenever the number of SPRequest objects exceeds this threshold, the following entry appears in the ULS logs:

"Potentially excessive number of SPRequest objects (number of objects) currently unreleased on thread number of thread. Ensure that this object or its parent (such as an SPWeb or SPSite object) is being properly disposed. Allocation Id for this object: {GUID}"

The best threshold varies according to the nature of your site and the applications running on it. When your sites are experiencing problems with performance, you should monitor your installation's ULS logs to understand how many SPRequest objects your site applications are creating. This helps you determine whether the designs of your sites and applications are creating too many SPRequest objects. Even if incorrect disposal of objects is not the cause of your performance problem, you might need to redesign your sites or custom site applications to reduce overall memory consumption caused by excessive proliferation of SPRequest objects.

Because the very low default threshold may not apply to many sites, you can change this threshold by editing the following registry subkey:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\HeapSettings

LocalSPRequestWarnCount = desired threshold value

After you determine that incorrect disposal of objects might be causing SPRequest objects to proliferate and unnecessarily increase the memory footprint of your sites, you can find specific instances of incorrect disposal by looking for the following two entries. Both messages point to cases where memory is being wasted because of incorrect disposal of SharePoint objects, and both relate to the number and state of SPRequest objects on a single thread:

  • "An SPRequest object was not disposed before the end of this thread. To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it. This object will now be disposed. Allocation Id: {GUID}To determine where this object was allocated, create a registry key at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\HeapSettings. Then create a new DWORD named SPRequestStackTrace with the value 1 under this key."

    This message indicates that an SPRequest object was disposed because it still existed at the end of a thread.

  • "An SPRequest object was reclaimed by the garbage collector instead of being explicitly freed. To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it. Allocation Id: {GUID} To determine where this object was allocated, create a registry key at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\HeapSettings. Then create a new DWORD named SPRequestStackTrace with the value 1 under this key."

    This message indicates that the garbage collector disposed of an SPRequest object.

To identify the code that causes the problem, you can search in the logs for entries that contain the allocation identifiers, or follow the instructions in the warnings and add the following subkey setting to the registry:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\HeapSettings SPRequestStackTrace = 1

This subkey setting ensures that the stack trace of the original SPRequest allocation (which occurs whenever an SPSite or SPWeb object is created) is added to the logs when these warnings occur.

The following sections describe several coding techniques you can use to ensure that the objects are disposed of properly.

Coding Techniques to Ensure Object Disposal

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

Dispose vs. Close Method Usage

The Dispose and Close methods for the SPWeb object and SPSite object function in the same way. The Dispose method calls the object's Close method. We recommend calling the Dispose method, instead of Close, because SPWeb and SPSite objects implement the IDisposable interface, and standard .NET Framework garbage collection calls the Dispose method to free any resources associated with the object from memory.

The using Clause

You can automatically dispose of SharePoint objects that implement the IDisposable interface by using the Microsoft Visual C# using statement.

The following code provides an example.

C#
String str;

using(SPSite oSPsite = new SPSite("http://server"))
{
  using(SPWeb oSPWeb = oSPSite.OpenWeb())
   {
       str = oSPWeb.Title;
       str = oSPWeb.Url;
   }
}  

Taking advantage of using statements can greatly simplify your code. As noted in the C# Reference (using Statement), the common language runtime translates using clauses into try and finally blocks, and any objects that implement the IDisposable interface are disposed for you. In many cases, however, using statements are not advisable, or must be used with some caution and understanding of what the runtime is doing. The following code example shows one case where you would not want the runtime to construct a finally block and dispose objects for you. In this case, SPContext returns an SPWeb object.

C#
// Do not do this. Dispose() is automatically called on SPWeb. 
using( SPWeb web = SPControl.GetContextWeb(HttpContext.Current)) { ... }

SPContext objects are managed by the SharePoint framework and should not be explicitly disposed in your code. This is true also for the SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_220.

You must be cautious and aware of what the runtime is doing whenever you combine SharePoint object model calls on the same line. Leaks arising from this scenario are among the hardest to find.

In the following code example, an SPSite object is instantiated but not disposed, because the runtime ensures disposal of only the SPWeb object returned by OpenWeb.

C#
void CombiningCallsLeak()
{
    using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb())
    {
        // ... New SPSite will be leaked.
    } // SPWeb object web.Dispose() automatically called.
}

You can fix this problem by nesting one using statement within another.

C#
void CombiningCallsBestPractice()
{
    using (SPSite siteCollection = new SPSite(SPContext.Current.Web.Url))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
        //Perform operations on site.
        } // SPWeb object web.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called.
}

If you are not performing any operations on the SPSite object, you could write this more succinctly, as in the following code example.

C#
void CombiningCallsBestPractice()
{
    using (SPSite siteCollection = new SPSite(SPContext.Current.Web.Url))
    using (SPWeb web = siteCollection.OpenWeb())
        {
        //Perform operations on site.
        } // SPWeb object web.Dispose() automatically called; SPSite object 
          // siteCollection.Dispose() automatically called.
}

In other cases, you must construct your own try, catch, and finally blocks. The most obvious examples are scenarios where you need to handle exceptions, and therefore must include a catch block. The following section provides guidelines on when and how to use try, catch, and finally blocks.

The try, catch, and finally Blocks

Using try, catch, and finally blocks obviously makes sense whenever you need to handle exceptions. Any code within a try/catch block should have a governing finally clause, which ensures that the objects that implement IDisposable are disposed. Notice that in the following code example you should fill the catch block with code that handles the exception. Never leave a catch block empty. Also note the best practice of testing for null before disposing.

C#
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();
}

Try and finally blocks or a using statement would be required to avoid potential leaks when you create a disposable object within a foreach block, as shown in the following code example.

C#
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.
 }

Response.Redirect with try, catch, and finally Blocks and using Statements

The finally block executes after calls to Response.Redirect in the try block. Response.Redirect ultimately generates a ThreadAbortException. When this exception is raised, the runtime executes all finally blocks before ending the thread. However, because the finally block can do an unbounded computation or cancel the ThreadAbortException, there is no guarantee that the thread will end. Therefore, before any redirection or transfer of processing can occur, you must dispose of the objects. If your code must redirect, implement it in a way similar to the following code example.

C#
String str;
SPSite oSPSite = null;
SPWeb oSPWeb = null;

try
{
   oSPSite = new SPSite("http://server");
   oSPWeb = oSPSite.OpenWeb(..);

   str = oSPWeb.Title;
   if(bDoRedirection)
   {
       if (oSPWeb != null)
          oSPWeb.Dispose();
    
       if (oSPSite != null)
          oSPSite.Dispose();

       Response.Redirect("newpage.aspx");
   }
}
catch(Exception e)
{
}
finally
{
   if (oSPWeb != null)
     oSPWeb.Dispose();

   if (oSPSite != null)
      oSPSite.Dispose();
}

Because a using clause instructs the runtime to create a finally block, whenever you use Response.Redirect within a using clause, ensure that objects are disposed properly. The following code example shows how you can do this.

C#
using (SPSite oSPSite = new SPSite("http://server"))
using (SPWeb oSPWeb = oSPSite.OpenWeb(..))
{
    if (bDoRedirection)
        Response.Redirect("newpage.aspx");
}

Recommendations to Reduce Long-Term Object Retention

You can reduce long-term retention of SharePoint objects by following these general recommendations.

  • If you create the object with a new operator, ensure that the creating application disposes of it.

    NoteNote:

    This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_110.

    Good Coding Practice #1

    Explicitly Disposing

    C#
    void CreatingSPSiteExplicitDisposeNoLeak()
    {
        SPSite siteCollection = null;
        try
        {
            siteCollection = new SPSite("http://moss");
        }
        finally
        {
            if (siteCollection != null)
                siteCollection.Dispose();
        }
    }
    

    Good Coding Practice #2

    Automatically Disposing

    C#
    CreatingSPSiteWithAutomaticDisposeNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
        } // SPSite object siteCollection.Dispose() is called automatically.
    }
    
  • Dispose of items created by SharePoint methods that return other SPWeb objects (such as OpenWeb).

    NoteNote:

    This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_120.

    Good Coding Practice

    C#
    void OpenWebNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
            } // SPWeb object web.Dispose() automatically called.
        }  // SPSite object siteCollection.Dispose() automatically called.
    }
    
  • Do not share any SPRequest object (and by extension any object that contains a reference to an SPRequest object) across threads. Any coding technique that shares an SPRequest object between two or more threads, or creates an SPRequest object on one thread and disposes it on another, is not supported. This means that you cannot store any object that holds a reference to an SPRequest object in a static variable. Do not, therefore, store SharePoint objects that implement IDisposable (such as SPWeb or SPSite) in static variables.

SPSite Objects

This section describes situations in which new SPSite objects are returned and must be disposed.

In general, any time a calling application uses the new SPSite constructors (any signature), it should call the Dispose method when it is finished using the object. If the SPSite object is obtained from GetContextSite, the calling application should not dispose of the object. Because the SPWeb and SPSite objects keep an internal list that is derived in this way, disposing of the object may cause the SharePoint object model to behave unpredictably. Internally, Windows SharePoint Services enumerates over this list after page completion to dispose of the objects properly.

SPSiteCollection Class

This section describes the methods, properties, or operators in the SPSiteCollection object that require the returned SPSite object to be closed after access.

SPSiteCollection.Add Method

The SPSiteCollection.Add method creates and returns a new SPSite object. You should dispose of any SPSite object returned from the SPSiteCollection.Add method.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_240.

Bad Coding Practice

C#
void SPSiteCollectionAddLeak()
{
    SPWebApplication webApp = new SPSite("http://moss").WebApplication;
    SPSiteCollection siteCollections = webApp.Sites;
    SPSite siteCollection = siteCollections.Add("sites/myNewSiteCollection", "DOMAIN\\User", 
      "roger.lamb@litwareinc.com");
    // SPSite siteCollection leak.
}

Good Coding Practice

C#
void SPSiteCollectionAddNoLeak()
{
    SPWebApplication webApp = new SPSite("http://moss").WebApplication;
    SPSiteCollection siteCollections = webApp.Sites;
    using (SPSite siteCollection = siteCollections.Add("sites/myNewSiteCollection", "DOMAIN\\User", 
      "roger.lamb@litwareinc.com"))
    {
    } // SPSite object siteCollection.Dispose() automatically called.
}

SPSiteCollection [ ] Index Operator

The SPSiteCollection [] index operator returns a new SPSite object for each access. An SPSite instance is created even if that object was already accessed. The following code samples demonstrate improper disposal of the SPSite object.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_230.

Bad Coding Practice #1

Using Index Operator

C#
void SPSiteCollectionIndexerLeak()
{
    using (SPSite siteCollectionOuter = new SPSite("http://moss"))
    {
        SPWebApplication webApp = siteCollectionOuter.WebApplication;
        SPSiteCollection siteCollections = webApp.Sites;

        SPSite siteCollectionInner = siteCollections[0];
        // SPSite siteCollectionInner leak. 
    } // SPSite object siteCollectionOuter.Dispose() automatically called.
}

Bad Coding Practice #2

Using ForEach Loop

C#
void SPSiteCollectionForEachLeak()
{
    using (SPSite siteCollectionOuter = new SPSite("http://moss"))
    {
        SPWebApplication webApp = siteCollectionOuter.WebApplication;
        SPSiteCollection siteCollections = webApp.Sites;

        foreach (SPSite siteCollectionInner in siteCollections)
        {
            // SPSite siteCollectionInner leak.
        }
    } // SPSite object siteCollectionOuter.Dispose() automatically called.
}

Good Coding Practice #1

Using Index Operator

C#
void SPSiteCollectionIndexerNoLeak()
{
    using (SPSite siteCollectionOuter = new SPSite("http://moss"))
    {
        SPSite siteCollectionInner = null;
        try
        {
            SPWebApplication webApp = siteCollectionOuter.WebApplication;
            SPSiteCollection siteCollections = webApp.Sites;

            siteCollectionInner = siteCollections[0];
        }
        finally
        {
            if (siteCollectionInner != null)
                siteCollectionInner.Dispose();
        }
    } // SPSite object siteCollectionOuter.Dispose() automatically called.
}

Good Coding Practice #2

Using ForEach Loop

C#
void SPSiteCollectionForEachNoLeak()
{
    using (SPSite siteCollectionOuter = new SPSite("http://moss"))
    {
        SPWebApplication webApp = siteCollectionOuter.WebApplication;
        SPSiteCollection siteCollections = webApp.Sites;

        foreach (SPSite siteCollectionInner in siteCollections)
        {
            try
            {
                // ...
            }
            finally
            {
                if(siteCollectionInner != null)
                    siteCollectionInner.Dispose();
            }
        }
    } // SPSite object siteCollectionOuter.Dispose() automatically called.
}

SPSite.AllWebs Property (SPWebCollection)

This section describes the methods, properties, or operators in the AllWebs property collection that require the SPWeb object to be closed after access.

SPSite.AllWebs.Add Method

The SPSite.AllWebs.Add method creates and returns an SPWeb object. You should dispose of any SPWeb object returned from SPSite.AllWebs.Add.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_150.

Bad Coding Practice

C#
void AllWebsAddLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        SPWeb web = siteCollection.AllWebs.Add("site-relative URL");
        // SPWeb object leaked.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

Good Coding Practice

C#
void AllWebsAddNoLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.AllWebs.Add("site-relative URL"))
        {
        } // SPWeb object web.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

SPWebCollection.Add Method

The SPWebCollection.Add method creates and returns an SPWeb object that needs to be disposed.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_200.

Bad Coding Practice

C#
void SPWebCollectionAddLeak(string strWebUrl)
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb outerWeb = siteCollection.OpenWeb())
        {
            SPWebCollection webCollection = siteCollection.AllWebs; // No AllWebs leak just getting reference.
            SPWeb innerWeb = webCollection.Add(strWebUrl);  // Must dispose of innerWeb.
            // innerWeb leak.
        } // SPWeb object outerWeb.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

Good Coding Practice

C#
void SPWebCollectionAddNoLeak(string strWebUrl)
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb outerWeb = siteCollection.OpenWeb())
        {
            SPWebCollection webCollection = siteCollection.AllWebs; // No AllWebs leak just getting reference.
            using (SPWeb innerWeb = webCollection.Add(strWebUrl))
            {
                //...
            }
        } // SPWeb object outerWeb.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

SPSite.AllWebs [ ] Index Operator

The SPSite.AllWebs [] index operator returns a new SPWeb instance each time it is accessed. An object is created during the indexing operation even if that object was already accessed. If not properly closed, the following code samples leave an SPWeb object in the .NET Framework garbage collector.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_130.

Bad Coding Practice

C#
void AllWebsForEachLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb outerWeb = siteCollection.OpenWeb())
        {
            foreach (SPWeb innerWeb in siteCollection.AllWebs)
            {
                // Explicitly dispose here to avoid out of memory leaks with large number of SPWeb objects.
            }
        } // SPWeb object outerWeb.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

Good Coding Practice #1

Using ForEach Loop

C#
void AllWebsForEachNoLeakOrMemoryOOM()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb outerWeb = siteCollection.OpenWeb())
        {
            foreach (SPWeb innerWeb in siteCollection.AllWebs)
            {
                try
                {
                    // ...
                }
                finally
                {
                    if(innerWeb != null)
                        innerWeb.Dispose();
                }
            }
        } // SPWeb object outerWeb.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

Good Coding Practice #2

Using Index Operator

C#
void AllWebsIndexerNoLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.AllWebs[0])
        {
        } // SPWeb object web.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

SPSite.OpenWeb and SPSite. SelfServiceCreateSite Methods

The OpenWeb method and SelfServiceCreateSite method (all signatures) create an SPWeb object and return it to the caller. This new object is not stored in the SPSite object and is not disposed of anywhere in the SPSite class. For this reason, you should dispose of any object created via these methods.

Bad Coding Practice

C#
void OpenWebLeak()
{
    using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb())
    {
        // SPSite leaked !
    } // SPWeb object web.Dispose() automatically called.
}

Good Coding Practice

C#
void OpenWebNoLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
        } // SPWeb object web.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called.
}

SPSite.RootWeb Property

An earlier version of this article indicated that the calling application should dispose of the SPSite.RootWeb property just before disposing of the SPSite object that is using it. This is no longer the official guidance. The dispose cleanup is handled automatically by the SharePoint framework. Additionally, SPSite properties LockIssue, Owner, and SecondaryContact used the RootWeb property internally. Given the updated guidance for RootWeb, it is no longer advisable to call the Dispose method on the SPSite.RootWeb property whenever any of these properties are used.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_140.

Good Coding Practice

C#
public void RootWebBestPractice()
{
    // New SPSite.
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        SPWeb rootWeb1 = siteCollection.RootWeb;
        // No explicit rootWeb1 dispose required.
    }  // siteCollection automatically disposed by implementing using().
    // rootWeb1 will be Disposed by SPSite.

    // SPContext and SPControl
    SPWeb rootWeb2 = SPContext.Current.Site.RootWeb;
    // Also would apply to SPControl.GetContextSite(Context);
    // No explicit rootWeb2 dispose required because it's obtained from SPContext.Current.Site.
}

Microsoft.Office.Server.UserProfiles.PersonalSite (Office SharePoint Server 2007 only)

The Microsoft.Office.Server.UserProfiles.PersonalSite returns an SPSite object that must be disposed.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_400.

Bad Coding Practice

C#
void PersonalSiteLeak()
{
    // Open a site collection.
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(siteCollection));
        UserProfile profile = profileManager.GetUserProfile("domain\\username");
        SPSite personalSite = profile.PersonalSite;    // Will leak.
    }
}

Good Coding Practice

C#
void PersonalSiteNoLeak()
{
    // Open a site collection.
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(siteCollection));
        UserProfile profile = profileManager.GetUserProfile("domain\\username");
        using (SPSite personalSite = profile.PersonalSite)
        {
            // ...
        }
    }
}

In another edge case, UserProfiles.PersonalSite leaks, as shown in the following code example.

C#
void PersonalSiteLeak()
{
    // Open a site collection.
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(siteCollection));
        UserProfile profile = profileManager.GetUserProfile("domain\\username");
        SPSite personalSite = profile.PersonalSite;    // Will leak.
    }
}

You can resolve this sort of leak by following the pattern shown in the following code example.

C#
void PersonalSiteNoLeak()
{
    // Open a site collection
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(siteCollection));
        UserProfile profile = profileManager.GetUserProfile("domain\\username");
        using (SPSite personalSite = profile.PersonalSite)
        {
            // ...
        }
    }
}

Also notice that you can improve performance (and avoid creating an SPSite object) by retrieving a PersonalSite object from the ProfileLoader, as shown in the following code example.

C#
UserProfile myProfile = ProfileLoader.GetProfileLoader().GetUserProfile();
using (SPSite personalSite = myProfile.PersonalSite)
{
     // ...
}

Additionally, if you are creating a Web Part for a My Site, you can use an instance of PersonalSite that does not need to be disposed.

C#
IPersonalPage currentMySitePage = this.Page as IPersonalPage;
if (currentMySitePage != null && !currentMySitePage.IsProfileError)
{
     SPSite personalSite = currentMySitePage.PersonalSite; // Will not leak.
     // ...
}

SPWeb Objects

This section describes the situations in which SPWeb objects are returned and may need to be disposed of.

SPWeb.ParentWeb Property

Updated Guidance

An earlier version of this article recommended that the calling application should dispose of the SPWeb.ParentWeb. This is no longer the official guidance. The dispose cleanup is handled automatically by the SharePoint framework.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_170.

Good Coding Practice

C#
using (SPSite site = new SPSite(http://localhost)) 
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["Announcements"];
        SPWeb parentWeb = list.ParentWeb; //No explicit dispose required.
    }
}

SPWeb.Webs Property

This section describes the methods, properties, or operators in the Webs property collection that require disposal of the SPWeb object after access.

SPWeb.Webs

The SPWeb.Webs property returns an SPWebCollection object. The SPWeb objects in this collection must be disposed.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_180.

Bad Coding Practice

C#
void WebsLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb outerWeb = siteCollection.OpenWeb())
        {
            foreach (SPWeb innerWeb in outerWeb.Webs)
            {
                // SPWeb innerWeb leak.
            }
        } // SPWeb object outerWeb.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

Good Coding Practice

C#
void WebsNoLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb outerWeb = siteCollection.OpenWeb())
        {
            foreach (SPWeb innerWeb in outerWeb.Webs)
            {
                try //Should be first statement after foreach.
                {
                    // ...
                }
                finally
                {
                    if(innerWeb != null)
                        innerWeb.Dispose();
                }
            }
        } // SPWeb object outerWeb.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

SPWeb.Webs.Add

The SPWeb.Webs.Add method (or Add) creates and returns a new SPWeb object. You should dispose of any SPWeb object returned from this method call.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_190.

Bad Coding Practice

C#
void WebsAddLeak(string strWebUrl)
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            SPWeb addedWeb = web.Webs.Add(strWebUrl);   // Will leak.

        } // SPWeb object web.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called.
}

Good Coding Practice

C#
void WebsAddNoLeak(string strWebUrl)
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            using (SPWeb addedWeb = web.Webs.Add(strWebUrl))
            {
                //..
            }

        } // SPWeb object web.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called.
}

SPWeb.Webs[] Index Operator

The SPWeb.Webs[] index operator returns a new SPWeb object for each access. An SPWeb is created by calling the OpenWeb method, even if that object was already accessed. The following code samples cause long-term retention of these objects in memory used by the .NET Framework.

Bad Coding Practice #1

Using For Loop

C#
int i;

SPWeb oSPWeb, oSPWeb2;
SPSite oSPSite = SPControl.GetContextSite(Context);

oSPWeb = oSPSite.OpenWeb();

for(i = 0;i < oSPWeb.Webs.Count;i++)
{
   oSPWeb2 = oSPWeb.Webs[i];
   BuildTableRow(oDisplayTable, "Web", oSPWeb2.Title);
}

Bad Coding Practice #2

Using ForEach Loop

C#
SPWeb oSPWeb, oSPWeb2;
SPSite oSPSite = SPControl.GetContextSite(Context);

oSPWeb = oSPSite.OpenWeb();

foreach(SPWeb oSPWeb2 in oSPWebe.Webs)
{
   BuildTableRow(oDisplayTable, "Web", oSPWeb2.Title);
}

The recommended fix is to dispose at the end of each loop.

Good Coding Practice #1

Using For Loop

C#
int i;

SPWeb oSPWeb, oSPWeb2;
SPSite oSPSite = SPControl.GetContextSite(Context);

oSPWeb = oSPSite.OpenWeb();

for(i = 0;i < oSPWeb.Webs.Count;i++)
{
   oSPWeb2 = oSPWeb.Webs[i];
   BuildTableRow(oDisplayTable, "Web", oSPWeb2.Title);
   oSPWeb2.Dispose();
}

oSPWeb.Dispose();

Good Coding Practice #2

Using ForEach Loop

C#
SPWeb oSPWeb, oSPWeb2;
SPSite oSPSite = SPControl.GetContextSite(Context);

oSPWeb = oSPSite.OpenWeb();

foreach(SPWeb oSPWeb2 in oSPWeb.Webs)
{
   BuildTableRow(oDisplayTable, "Web", oSPWeb2.Title);
   oSPWeb2.Dispose();
}

oSPWeb.Dispose();

Good Coding Practice #3

Using For Loop with Automatic Disposal

C#
int i;

SPWeb oSPWeb, oSPWeb2;
SPSite oSPSite = SPControl.GetContextSite(Context);

using(oSPWeb = oSPSite.OpenWeb())
{
   for(i = 0;i < oSPWeb.Webs.Count;i++)
   {
      Using(oSPWeb2 = oSPWeb.Webs[i])
      {
         BuildTableRow(oDisplayTable, "Web", oSPWeb2.Title);
      }
   }
}

Other Objects That Require Disposal

This section describes when to call the Dispose method on other SharePoint objects.

Microsoft.SharePoint.Portal.SiteData.Area.Web Property

The Web property returns a new SPWeb object each time it is accessed. Any use of the Area.Web property should have a corresponding call to the Dispose method. Although the Area and AreaManager classes are now obsolete in Office SharePoint Server 2007, this remains a concern when migrating legacy code.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_500.

Bad Coding Practice

C#
void AreaWebLeak()
{
    // AreaManager and Area are obsolete in SharePoint Server, but this
    // should still be noted.
    Area area = AreaManager.GetArea(PortalContext.Current, new Guid("{GUID}"));
    string str = area.Web.Title;
    // SPWeb area.Web leak.
}

Good Coding Practice

C#
public void AreaWebNoLeak()
{
    // AreaManager and Area are obsolete in MOSS but this should still be noted
    Area area = AreaManager.GetArea(PortalContext.Current, new Guid("{GUID}"));
    using (SPWeb areaWeb = area.Web)
    {
        string str = areaWeb.Title;
    }
}

SPControl.GetContextSite and SPControl.GetContextWeb Methods

If the object is obtained from the SharePoint context objects (GetContextSite method and GetContextWeb method), the calling application should not call the Dispose method on the object. Doing so may cause the SharePoint object model to behave unpredictably or fail. This is due to an internal list that is kept in the SPSite and SPWeb objects derived in this way. Internally, the object model enumerates over this list after page completion to dispose of the objects properly.

You should still dispose of an object that is created from these objects, for example, if a Web site is opened from an SPSite object that you obtained by using the GetContextSite method.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_210.

Bad Coding Practice

C#
void SPControlBADPractice()
{
    SPSite siteCollection = SPControl.GetContextSite(Context);
    siteCollection.Dispose();   // DO NOT DO THIS
    SPWeb web = SPControl.GetContextWeb(Context);
    web.Dispose();  // DO NOT DO THIS.
}

Good Coding Practice

C#
void SPControlBestPractice()
{
    SPSite siteCollection = SPControl.GetContextSite(Context);
    SPWeb web = SPControl.GetContextWeb(Context);
    // Do NOT call Dispose().
}

Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager

The SPLimitedWebPartManager class contains a reference to an internal SPWeb object that must be disposed.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_160.

Bad Coding Practice

C#
void SPLimitedWebPartManagerLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            SPFile page = web.GetFile("Source_Folder_Name/Source_Page");
            SPLimitedWebPartManager webPartManager =
                page.GetLimitedWebPartManager(PersonalizationScope.Shared);
            // SPWeb object webPartManager.Web leaked.
        } // SPWeb object web.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

Good Coding Practice

C#
void SPLimitedWebPartManagerLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            SPFile page = web.GetFile("Source_Folder_Name/Source_Page");
            SPLimitedWebPartManager webPartManager =
                page.GetLimitedWebPartManager(PersonalizationScope.Shared);
                webPartManaber.Web.Dispose();
        } // SPWeb object web.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

Microsoft.SharePoint.Publishing.PublishingWeb (SharePoint Server 2007 Only)

The GetPublishingWebs method of the PublishingWeb class returns a PublishingWebCollection object. You must call the Close method on each enumerated innerPubWeb object. When you are calling only the GetPublishingWeb method, you are not required to call Close.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_300.

Bad Coding Practice

C#
void PublishingWebCollectionLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            // Passing in SPWeb object that you own, no dispose needed on
            // outerPubWeb.
            PublishingWeb outerPubWeb = PublishingWeb.GetPublishingWeb(web);

            PublishingWebCollection pubWebCollection = outerPubWeb.GetPublishingWebs();
            foreach (PublishingWeb innerPubWeb in pubWebCollection)
            {
                // innerPubWeb leak.
            }
            // PublishingWeb will leak for each innerPubWeb referenced
        } // SPWeb object web.Dispose() automatically called.
    } // SPSite object siteCollection.Dispose() automatically called.
}

Good Coding Practice

C#
void PublishingWebCollectionNoLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            // Passing in SPWeb object that you own, no dispose needed on
            // outerPubWeb.
            PublishingWeb outerPubWeb = PublishingWeb.GetPublishingWeb(web);
            PublishingWebCollection pubWebCollection = outerPubWeb.GetPublishingWebs();
            foreach (PublishingWeb innerPubWeb in pubWebCollection)
            {
                try
                {
                    // ...
                }
                finally
                {
                    if(innerPubWeb != null)
                        innerPubWeb.Close();
                }
            }
        }  // SPWeb object web.Dispose() automatically called.
    } // SPSite object siteCollection.Dispose() automatically called.
}
NoteNote:

There is a similar requirement to call Close on each PublishingWeb object created by calling the Add method on the PublishingWebCollection returned by Microsoft.SharePoint.Publishing.PublishingWebCollection.GetPublishingWebs. For a code example, see the GetPublishingWebs method in the Microsoft Office SharePoint Server 2007 SDK. This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_310.

The Microsoft.SharePoint.Publishing.PublishingWeb.GetVariation method returns a PublishingWeb object that must be disposed.

NoteNote:

This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_320.

Bad Coding Practice

C#
void GetVariationLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);  // Passing in SPWeb object, so no Close() needed
            VariationLabel variationLabel = Variations.Current.UserAccessibleLabels[0];
            PublishingWeb variationPublishingWeb = publishingWeb.GetVariation(variationLabel);  // Must be Closed().
            // ...
        } // SPWeb object outerWeb.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

Good Coding Practice

C#
void GetVariationNoLeak()
{
    using (SPSite siteCollection = new SPSite("http://moss"))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            PublishingWeb variationPublishingWeb = null;
            try
            {
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);  // Passing in SPWeb object, so no Close() needed.
                VariationLabel variationLabel = Variations.Current.UserAccessibleLabels[0];
                variationPublishingWeb = publishingWeb.GetVariation(variationLabel);  // Must be Closed().
                // ...
            }
            finally
            {
                if(variationPublishingWeb != null)
                    variationPublishingWeb.Close();
            }
        } // SPWeb object web.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called. 
}

Cross Method Dispose Patterns

The following example demonstrates the common practice of holding onto the SPSite and SPWeb objects across methods in a class. Sometimes this design pattern is required, but ensure that you do not overlook the appropriate time to call Dispose when you are finished with the cross method calls. The following code example shows a pattern where SPSite and SPWeb leak when the class goes out of scope.

C++
public class CrossMethodLeak
{
    private SPSite _siteCollection = null;
    private SPWeb _web = null;

    public void MethodA()
    {
        _siteCollection = new SPSite("http://moss");
        _web = _siteCollection.OpenWeb();
    }

    public void MethodB()
    {
        if (_web != null)
        {
            string title = _web.Title;
        }
    }

    public void MethodC()
    {
        if (_web != null)
        {
            string name = _web.Name;
        }
    }
}

Conclusion

Because many SharePoint objects implement the IDisposable interface, you must take care when using these objects to avoid retaining them in memory. By following the guidelines for disposing of SharePoint objects, as described in this article, you can help to ensure reliability of your Windows SharePoint Services custom code.

Acknowledgements

We would like to thank the following people for their input and guidance in creating this document:

  • Steve Sheppard, Microsoft Corporation

  • Chris Gideon, Microsoft Corporation

  • Rashid Aga, Microsoft Corporation

Additional Resources

Community Content   What is Community Content?
Add new content RSS  Annotations
Dispose of an SPWeb that is being returned from a function      spr789 ... Noelle Mallory - MSFT   |   Edit   |   Show History

We have code where at times we'll be returning an SPWeb object from a function. So for example:

public SPWeb getDeptWeb()
{
SPWeb deptWeb = SpSite.OpenWeb(SpContext.Web.ID);
...
return deptWeb;
}

How can we dispose of the SPWeb object in this instance? Or is it sufficient to dispose it where we're accepting the returned parameter?

[Noelle Mallory - MSFT] Please post questions to the MSDN Forums at http://forums.microsoft.com/msdn. You will likely get a quicker response through the forum than through the Community Content.

Tags What's this?: Add a tag
Flag as ContentBug
SPList.ParentWeb      LMC2 ... Keith Dahlby   |   Edit   |   Show History

What about SPList.ParentWeb ? The disposal behaviour should be documented in any function or property returning an SPSite or SPWeb object...

[dahlbyk] In most cases, SPList.ParentWeb will return the SPWeb from which its parent SPListCollection was created and should not be disposed. To be sure, you can check like this:

  
void SetListDescription(SPList list)
{
try
{
list.Description = list.Title + " in " + list.ParentWeb.Title;
}
finally
{
if(list.ParentWeb != list.Lists.Web)
list.ParentWeb.Dispose();
}
}

This also applies to BreakRoleInheritance() and other methods/properties with internal calls to ParentWeb. http://solutionizing.net/2009/01/09/splist-parentweb-leaks-revisited/

Disposal of RootWeb      MIKEY MIGEE   |   Edit   |   Show History
Be sure not to dispose RootWeb within The context site.
Tags What's this?: Add a tag
Flag as ContentBug
Good Link      Saroj Jha ... AndersR   |   Edit   |   Show History

Hi look for the good article by Roger Lamb at:
http://blogs.msdn.com/rogerla/archive/2008/02/12/sharepoint-2007-and-wss-3-0-dispose-patterns-by-example.aspx

I thought that finally block is implemented in the try-catch-finally , so instead of going for

if(bDoRedirection)
{
if (oSPWeb != null)
oSPWeb.Dispose();

if (oSPSite != null)
oSPSite.Dispose();

Response.Redirect("newpage.aspx");
}

We can always place the
Response.Redirect("newpage.aspx");
in the finally block. Please suggest if i am incorrect.

Thanks
Saroj

You are absolutely right.

Finally will always be called no matter what, even if you redirect. The function must be allowed to finish to unwind the call stack.

Anders Rask

VB.NET      Paul Liebrand   |   Edit   |   Show History

Some people tend to forget this, but as a reminder, VB.NET also has a USING syntax. For example:

Using site AsNew SPSite(http://server/)
Using web As SPWeb = site.OpenWeb()
Console.WriteLine(web.Title)
EndUsing
EndUsing


Thanks,

Paul Liebrand
http://liebrand.wordpress.com



SPWorkflowActivationProperties.Web      anonymous coward   |   Edit   |   Show History
According to the thread Random NullReferenceExceptions at OpenWebInternal, objects from SPWorkflowActivationProperties.Web must be disposed.
Tags What's this?: Add a tag
Flag as ContentBug
The following log entries will indicate having problems with this very disposal      AllTheGoodNamesAreInUse   |   Edit   |   Show History

(implemented by your own or 3rd party non-ms code)

your Sharepoint server at least, will have in it's logs at this location:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\LOGS

(you know what to replace c with anyway)

the following message(s):

Potentially excessive number of SPRequest objects (10) currently unreleased on thread 9. Ensure that this object or its parent (such as an SPWeb or SPSite) is being properly disposed. Allocation Id for this object: {YOUR GUID} Stack trace of current allocation:

etc. etc.

This just as a pointer, I sure got this from a 3rd party.

Anyone got hints on how to use the appid to find more informaion? I guess I will have to find the application pool for that ID; enable deeper IIS logging et cetera?

In our case, we get failures trying to move files / folders.

Flag as ContentBug
ParentWeb and Web on SPList, SPListItem      danleis ... Keith Dahlby   |   Edit   |   Show History

SPList and SPListItem objects keep their references of the SPWeb object on which they were created. Therefore SPList.ParentWeb and SPListItem.Web objects should not be disposed after usage. When the owner web is disposed, the SPList and SPListItem objects created from that web, cannot be used any longer.

[dahlbyk] I am deleting an example of a helper method that returns an SPListItem from an SPWeb that is disposed - this is not a good idea. Items that are created from an SPWeb should never be returned from the method where the SPWeb is created, especially if the SPWeb is disposed before the object is returned.

Tags What's this?: Add a tag
Flag as ContentBug
SPContext      Seth Hildebrand   |   Edit   |   Show History
I often use SPContext.Current.Site. I'm assuming that this should NOT be disposed. Is that correct thinking? Also, what about SPContext.Current.Site.RootWeb?
Tags What's this?: Add a tag
Flag as ContentBug
RE:Good Link      Reza Alirezaei - MVP   |   Edit   |   Show History

Saroj Jha,

Putting Response.Redirect() in the finally block gets hit no matter what. Read the end of my blog post here :

http://blogs.devhorizon.com/reza/?p=472


RE:SPContext      Reza Alirezaei - MVP   |   Edit   |   Show History
You do not need explicitly call Dispose() on any variation of SPContext object and SPSite.RootWeb property. This would interfere with the current context which will be disposed of by SharePoint and results in unexpected behaviors.
Post your questions to the designated forums pls      Reza Alirezaei - MVP   |   Edit   |   Show History

Ladies and gentlemen,

Please do not post your questions here as the community content is a place to add content in addition to what the Parent object :) (the artile) offers. Microsoft maintains very active Forums at http://forums.microsoft.com/msdn in which you can get much quicker answer and possibility of more experts see your questions. Thanks!

Flag as ContentBug
Disposal of SPContext.Current.Site.RootWeb      awell ... AndersR   |   Edit   |   Show History

Hi.

I believe this should be mentioned here as there seems to be some confusion:

SPContext.Current.Site.RootWeb

This property is interesting. I did some playing with it.

I believe Mikey and Reza are mistaken by saying you should not call Dispose() on this object (contradicts what the article says?!?). Without using Dispose() on it, I was getting lots of the warnings in the log files about it.

So, after reading this article, I explicitly Dispose()'d all SPWeb objects that had been retrieved using the RootWeb property. All seemed to work well and all the warnings in the log files went away.

BUT: I noticed I was getting the "trying to use an SPWeb object that has been closed or disposed" error when my controls were executing in places like, /Forms/AllItems.aspx on a library or list in the root web.

In this case, I discovered that the object returned by SPContext.Current.Site.RootWeb == SPContext.Current.Web !!!!!

Of course if this object is disposed it causes the error.

This behaviour doesn't seem to be documented in this article.

Anyway, here's what I did to make my controls work at any level in my structure, and not create memory leaks!!!

SPWeb w = SPContext.Current.Site.RootWeb;

//make use of w here
if (w != SPContext.Current.Web) w.Dispose();

Hope this saves someone the same headache as I currently have.

-Adrian

Ouch! Dont dispose the current thread -ever!

It might seem like its working, but try for example to add a webpart under the webpart in which you dispose current web. Then try to go in edit mode of that web part. Then all *** breaks loose...

The article say that you should dispose all the sites that *you* are responsible for. Hence if you "new" an object you should dispose of it again.

Current web is created by the portal and it needs it to function properly, so dont dispose it.

hth

Anders Rask

Disposal of SPContext.Current.Site.RootWeb      THE RAZI ... Thomas Lee   |   Edit   |   Show History

This article is still not updated with the issue yet , but this can casue some real headaches, if not deal with properly.

For newbies , do note that there are lot of books, and articles reference this article,so be cautious.

All this seems like a Rube Goldberg contraption !      ginolee   |   Edit   |   Show History
Can you guys over at Microsoft make the API more sophisticated so that there are fewer and simpler rules to follow ?

The fact that you are reflecting a set of complicated rules onto the end programmer suggests that your API is lacking
some simple intelligence that would make disposal of objects easier to manage.

As it is, it's pretty unimpressive to have to follow a couple dozen rules for memory management.

Alternatively, add a tool to Visual Studio, which will identify and fix most of these cases automatically.

As a comparison, if I remember my C++ correctly, there were 3 basic rules:
1. If you did a 'new' of an object, you were responsible for cleaning it up.
2. If you passed in an existing object, you did not clean it up.
3. Any exception to rules #1 and #2 were documented in the API.

Even with these 3 basic rules, people typically didn't always get it right.

Which is why we now have automatic garbage collectors.

It sounds like a new tool SPDisposeCheck will be coming out within the next couple months. This tool, if it's solid, should help a lot.
Tags What's this?: Add a tag
Flag as ContentBug
SPDisposeCheck v1.3.1 released      AndersR   |   Edit   |   Show History
SPDisposeCheck makes it easier to check your (or your fellow coders) code for dispose related memory leaks.

Beware of false positives though..

http://code.msdn.microsoft.com/SPDisposeCheck

Anders Rask
Tags What's this?: Add a tag
Flag as ContentBug
Cross Method Dispose Pattern      jason.t   |   Edit   |   Show History

It's not listed in the article above, but I've found that using a destructor/finalizer to dispose of SPSite or SPWeb prevents memory leaks when using these objects as member variables.

public MyClass
{
private SPSite _site;
private SPWeb _web;

MyClass()
{
_site = new SPSite(url);
_web = _site.OpenWeb();
}

//do stuff w/member variables


//dispose of object to prevent memory leaks
~MyClass()
{
if ( _site == null )
{
_site.Dispose();
_site = null;
}

if ( _web == null )
{
_web.Dispose();
_web = null;
}
}
}

Microsoft, use managed code FGS      Meat Popcicle   |   Edit   |   Show History

Big headache. Having to dispose everything. Microsoft should implement a method like RunElevated security that sorts out disposals. Those poor sacks that built the GC, pretty useless now isn't it. Pinned managed objects.

We have a 30 GB content database running on or QA servers. When the search index runs the memory usage eventually gets up to 27 GBs. Now what? I've reviewed all the code according to the best practices. Still does the same thing. That's why I'm here.

Response.Redirect terminates the thread? Stops execution? does it stop before it disposes of SPContext objects???

Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker