使用秒表来评估应用程序的使用情况

时间:2012-05-19 22:22:54

标签: c# oop class stopwatch

您好我正在尝试创建一个可以在我的项目中使用的全局类,我打算将其用作我的默认模板,我是新手所以请耐心等待;)

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

我怀疑我的设计存在缺陷,因为我想要秒表Masterstopwatch =新秒表();要在全球范围内宣布而不使用某种方法,我怀疑这是不可行的,但我需要问一下 感谢

1 个答案:

答案 0 :(得分:6)

听起来你需要Singleton Pattern

如果您按照以下方式在秒表周围声明包装,则可以在应用中的任何位置使用它并访问秒表的相同实例。

// 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();
    }
}