I would like to create an abstract class with an abstract method which can measure how long it takes to run.
public abstract class Monitor
{
protected Stopwatch Timer = Stopwatch.StartNew();
public abstract void Run();
}
public class Concrete : Monitor
{
public override void Run()
{
base.Timer.Start();
//DoSomething
base.Timer.Stop();
}
}
However, implementers of the abstract class should not be calling the Start / Stop methods directly, so we can try to hide the implementation.
public abstract class Monitor
{
private Stopwatch Timer = Stopwatch.StartNew();
public virtual void Run()
{
Timer.Start();
Timer.Stop();
}
}
But as you can see this won’t work very well.
How can i ensure that all implementations of the base class will call Start /Stop and yet allow implementation code to run in between? Could events help me here, if so how?
Use the template method pattern: