Using a stopwatch to benchmark application usage
c#, class, oop, stopwatch
Solution
Sounds like you need the Singleton Pattern.
If you declare a wrapper around stopwatch as follows you can use it anywhere in your app and access the same instance of a Stopwatch.
// Declare singleton wrapper of a stopwatch, which instantiates stopwatch
// on construction
public class StopwatchProxy
{
private Stopwatch _stopwatch;
private static readonly StopwatchProxy _stopwatchProxy = new StopwatchProxy();
private StopwatchProxy()
{
_stopwatch = new Stopwatch();
}
public Stopwatch Stopwatch { get { return _stopwatch; } }
public static StopwatchProxy Instance
{
get { return _stopwatchProxy; }
}
}
// Use singleton
class Foo
{
void Foo()
{
// Stopwatch instance here
StopwatchProxy.Instance.Stopwatch.Start();
}
}
class Bar
{
void Bar()
{
// Is the same instance as here
StopwatchProxy.Instance.Stopwatch.Stop();
}
}
Problem
Hi I am trying to make a global class that I can use in my projects, I intend to use this as my default template, I am a newbie so please be patient ;) ``` Stopwatch Masterstopwatch = new Stopwatch(); #if DEBUG private static void ApplicationLogStart() { StartTime = DateTime.Now; Masterstopwatch.Start(); String eventName = "Program Loaded"; String errorDetails = "Program has started Succesfully"; DataLogEntry(eventName, errorDetails); } private static void ApplicationLogclosing() { String eventName = "Program is closing"; String errorDetails = "Program has closed Succesfully"; DataLogEntry(eventName, errorDetails); StopTime = DateTime.Now; Masterstopwatch.Stop(); Benchmark(StartTime,StopTime,Masterstopwatch.Elapsed); } #endif ``` I suspect that I am fundimently flawed in my design as I want the Stopwatch Masterstopwatch = new Stopwatch(); to be declared globally without using a method, I suspect that this is not posible, but I need to ask Thanks