What is SPMonitoredScope and how can I use it?


While reflecting on some Microsoft code I came across a class called SPMonitoredScope. Not really knowing what it was I Googled (sorry I mean, used my favourite search engine) to see what it is.

The SPMonitoredScope class can be used to monitor performance and resource usage in your application by using it in a simple code block. The plus side about using the monitored scopes are that you can track down and find bottlenecks as well as do some intial performance monitoring while doing your development.

In order to use the SPMonitoredScope you’ll need to add a using statement for Microsoft.SharePoint.Utilities and then wrap you code in a statement like this;

Using(new SPMonitoredScope("CallMethod1 Monitored Scope"))
{
 var result = CallMyProcess(true);
}

So once this is in your code how does it help with performance? When the code is running, by opening up the developer dashboard on the page where you code is excuting. If you look at the picture below you will see I’ve added three monitored scopes in my code. (Called Method 1, 2, 3)

You can see that the CallMethod3 is the one causing this page to take a long time to load.

You can also nest your scopes.

using (new SPMonitoredScope("My Monitored Scope"))
           {
                Controls.Add(new Literal { Text = "One Level deep! " });

                using (new SPMonitoredScope("My Sub-Monitored Scope"))
                {
                 Controls.Add(new Literal { Text = "Two Levels deep" });

                 using (new SPMonitoredScope("My Sub-Sub-Monitored Scope"))
                 {
                   Controls.Add(new Literal { Text = "I'm three levels deep!" });
                 }
                 using (new SPMonitoredScope("Another deep scope"))
                 {
                  Controls.Add(new Literal { Text = "I'm also three levels deep!" });
                 }
               }

Please note that the limitation of this class, is that it is NOT available in sandboxed solutions.

Advertisements