I am writing a very simple utility class with the aim to measure the time executed for any method passed in (of any type).
In my case Membership.ValidateUser(model.UserName, model.Password)
return bool so I get an exception.
I would like if would be possible write a utililty class of this type an a sample of code on how to fix it. Does it make sense use dynamic in stead of action?
Tracing.Log(Membership.ValidateUser(model.UserName, model.Password), "Membership.ValidateUser");
public static class Tracing
{
public static void Log(Action action, string message)
{
// Default details for the Log
string sSource = "TRACE";
string sLog = "Application";
// Create the Log
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
// Measure time Elapsed for an Action
Stopwatch stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
TimeSpan timeElapsed = stopwatch.Elapsed;
// Write the Log
EventLog.WriteEntry(sSource, "TIME-ELAPSED: " + timeElapsed .ToString() + message, EventLogEntryType.Warning, 234);
}
}
Your current code tries to execute ValidateUser
and use the result as the method argument. You want to pass in an action without first executing ValidateUser
.
You just need to convert your method call to use a lambda expression to create a delegate:
Tracing.Log(() => Membership.ValidateUser(model.UserName, model.Password),
"Membership.ValidateUser");
(Dynamic typing wouldn't affect this at all.)
Note that timing a single method execution is often going to give you very noisy results, unless it's a reasonably long method call. Usually to benchmark a single method you'd want to execute the method many times, until you've spent a reasonably significant amount of time executing it. Using Stopwatch
helps, but it doesn't get past the fact that your method may require very few ticks to complete, and if the thread is pre-empted, that will have a disproportionate effect on the results.
EDIT: I'm assuming that you want to use this purely for benchmarking. If you're trying to do this tracing in your real application, you'll want a less invasive approach. Look at Mini-MVC-Profiler for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With