我有一个静态计时器类,任何网页都会调用它来计算每个页面构建的时间.
我的问题是静态类线程安全吗?在我的示例中,并发用户会导致启动和停止时间出现问题吗?例如,不同的线程覆盖我的开始和停止值.
public static class Timer
{
private static DateTime _startTime;
private static DateTime _stopTime;
/// <summary>
/// Gets the amount of time taken in milliseconds
/// </summary>
/// <returns></returns>
public static decimal Duration()
{
TimeSpan duration = _stopTime - _startTime;
return duration.Milliseconds;
}
public static void Start()
{
_startTime = DateTime.Now;
}
public static void Stop()
{
_stopTime = DateTime.Now;
}
}
Run Code Online (Sandbox Code Playgroud)
这个类应该是非静态类吗?
(这个类将从asp.net主页调用.)
以下是一个无意义的扩展方法示例:
public static class MyExtensions
{
public static int MyExtensionMethod(this MyType e)
{
int x = 1;
x = 2;
return x
}
}
Run Code Online (Sandbox Code Playgroud)
假设执行线程完成并包括该行:
x = 2;
Run Code Online (Sandbox Code Playgroud)
处理器然后上下文切换,另一个线程进入相同的方法并完成该行:
int x = 1;
Run Code Online (Sandbox Code Playgroud)
假设第一个线程创建并分配的变量"x"在一个单独的堆栈上由第二个创建并分配的变量"x",我是否正确,这意味着该方法是可重入的?