【问题标题】:Using a stopwatch to benchmark application usage使用秒表对应用程序使用情况进行基准测试
【发布时间】:2012-05-27 00:14:04
【问题描述】:

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

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 = new Stopwatch();要在不使用方法的情况下全局声明,我怀疑这是不可能的,但我需要问 谢谢

【问题讨论】:

    标签: c# oop class stopwatch


    【解决方案1】:

    听起来您需要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();
        }
    }
    

    【讨论】:

    • 我在这里看不到正确的单例。这根本不是线程安全的。
    • 我很确定,因为 .NET 运行时确保每个 AppDomain 只调用一次 private static readonly _stopwatchProxy = new StopwatchProxy()。有关信息,请参阅msdn.microsoft.com/en-us/library/aa645612.aspx
    • 哈。不知道那件事。你每天都会学到新东西。
    • 公平地说,我还必须检查 ;-) 保存双重锁定和所有的 shebang。当被问到一个迂腐的面试问题时也很方便!
    猜你喜欢
    • 2015-03-06
    • 2017-05-17
    • 2010-10-19
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多