gpt4 book ai didi

c# - 使用秒表对应用程序使用情况进行基准测试

转载 作者:行者123 更新时间:2023-11-30 14:36:20 25 4
gpt4 key购买 nike

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

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

我怀疑我的设计存在根本性缺陷,因为我想要 Stopwatch Masterstopwatch = new Stopwatch();在不使用方法的情况下全局声明,我怀疑这是不可能的,但我需要问谢谢

最佳答案

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

关于c# - 使用秒表对应用程序使用情况进行基准测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10669262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com