静态方法线程安全吗 [英] Are static methods thread safe
问题描述
我有一个静态计时器类,任何网页都会调用它来计算构建每个页面所用的时间.
I have a static timer class which will be called by ANY webpage to calculate how long each page has taken to be constructed.
我的问题是静态类线程安全吗?在我的示例中,并发用户是否会导致我的开始和停止时间出现问题?例如,不同的线程覆盖了我的开始和停止值.
My question is are Static classes thread safe? In my example will concurrent users cause a problem with my start and stop times? e.g a different threads overwriting my start and stop values.
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;
}
}
这个类应该是非静态类吗?
Should this class be a non-static class?
(该类将从 asp.net 母版页调用.)
(This class will called from the asp.net masterpage.)
推荐答案
静态方法不是固有线程安全的.CLR 对它们的处理与实例方法没有区别.不同之处在于通常应该尝试使它们成为线程安全的.(我想不出任何不是线程安全的 .NET BCL 静态方法.)实例方法通常不是线程安全的,因为典型的模式是创建一个对象并从一个线程重复使用它,如果它确实必须在多个线程中使用,所涉及的协调包括确保安全使用对象.在很多情况下,在协调代码中比在对象本身中更合适.(通常您希望使整个操作序列有效地原子化 - 这是在对象中无法完成的事情.)
Static methods aren't inherently thread-safe. They're treated no differently by the CLR than instance methods. The difference is that one should generally try to make them thread-safe. (I can't think of any .NET BCL static methods which aren't thread-safe.) Instance methods are often not thread-safe because the typical pattern is to create an object and use it repeatedly from one thread, and if it does have to be used from multiple threads, the co-ordination involved includes making sure that the object is used safely. In very many cases that's more appropriate to do in the co-ordinating code than in the object itself. (Usually you want to make whole sequences of operations effectively atomic - something which can't be done within the object.)
您的 Timer
类绝对不是线程安全的:两个线程可以轻松地访问彼此的数据,并且在计算持续时间时没有什么可以阻止线程使用陈旧"数据.
Your Timer
class is most definitely not thread-safe: two threads can stomp on each other's data with ease, and there's nothing to stop a thread from using "stale" data when calculating the duration.
使用秒表
类 - 这就是它的用途.诚然,如果您想使用来自多个线程的一个实例,您需要采取正常步骤来确保安全,但总的来说,您会处于一个更好的位置.诚然,Stopwatch
也远非完美 - 请参阅这个问题和下面的评论了解更多详情 -但这至少是该类型的设计目的.(谁知道呢,它可能会在一段时间内修复...)
Use the Stopwatch
class instead - that's what it's there for. Admittedly if you want to use one instance from multiple threads you'll need to take the normal steps to ensure safety, but you'll be in a much better position in general. Admittedly Stopwatch
is far from perfect too - see this question and the comment below for more details - but it is at least what the type is designed for. (Who knows, it may be fixed some time...)
这篇关于静态方法线程安全吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!