Search in Help for developer site.

Thursday 11 May 2017

Calculate time taken by an Action Method in ASP NET MVC

Calculate time taken by an Action Method in ASP.NET MVC

What is Action Filter?

An Action Filter consists of logic that runs directly before or directly after an action method runs. You can use action filters for logging, Tracing, authentication, output caching, or other tasks.

Use of time taken by an Action Method

When we know that how much time an Action Method is taking when it completes its execution. The time can be used in many scenarios like Application slowness issue.
We shall be able to identify which Action Method is taking time above an average time and that action method can be tuned.

Lets get started

 Create a new asp.net mvc project in visual studio.

After creating the project there would be a App_Start folder.
All the filters relies in App_Start folder so we will be adding our filter in app_start folder.

Add a new class with the name of ActionTimeFilter and inherit it by ActionFilterAttribute class.

ActionFilterAttribute Class has two methods OnActionExecuting and OnActionExecuted.

OnActionExecuting method executes before an action method is executed and OnActionExecuted method executes after an action method is executed.

So lets override them


using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TimeTakenByActionMethodDemo.App_Start
{
    public class ActionTimeFilter:ActionFilterAttribute
    {
        Stopwatch stopwatch = new Stopwatch();
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            stopwatch.Restart();
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            stopwatch.Stop();
            TimeSpan timeTakenByActionMethod = stopwatch.Elapsed;
            //save this time to database for tunning purpose or any other.
        }
    }

}

As you can see i use Stopwatch to calculate the time so these above methods will executes for every action method that exists in your application.

If you don't want to run this filter on every action method then remove the filter from Global Filters collection and decorate those action method with this filter. So that this filter will only executes for the decorated action method. see the following example.


  [ActionTimeFilter]
        public ActionResult Index()
        {
            return View();

        }
Now only the Index action method shall be traced.

Next step is to register our filter into the Global Filters collection.


   protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //registering filters
            GlobalFilters.Filters.Add(new ActionTimeFilter());

        }

Now Lets put a break point on both methods and run the application to see the elapsed time.

As you can see the elapsed time is 4 seconds and some milliseconds.
Now you can save this Time into the database and you can identify which action method is taking long time to execute.


What do you think?

I hope you found this article useful, do put your comments or any query in the comments section.Thank you!!!


3 comments:

  1. That's good for testing purpose. unless it might get slow your Application.. i'm not sure about it.

    ReplyDelete
  2. BTW it's really informative.

    ReplyDelete