不要使用System.Threading.Timer同步? [英] Don't use System.Threading.Timer to synchronize?
问题描述
我有一些code看起来像这样:
I have some code looking like this:
using System.Threading;
public sealed class MyClass : IDisposable {
private readonly Timer _timer;
public MyClass() {
_timer = new Timer(MyCallback);
}
public void SomeMethod() {
lock (_timer) {
...
}
}
...
}
当我运行code分析(FxCop的)我得到错误信息
CA2002:Microsoft.Reliability:对类型的引用'定时''MyClass.SomeMethod'锁。与针对对象具有很强的身份锁定替换此。
When I run code analysis (FxCop) I get the error message
CA2002 : Microsoft.Reliability : 'MyClass.SomeMethod' locks on a reference of type 'Timer'. Replace this with a lock against an object with strong-identity.
一个对象,据说有微弱的身份时,它可以跨应用程序域边界直接访问。
An object is said to have a weak identity when it can be directly accessed across application domain boundaries.
如何让我的私人计时器对象跨应用程序域进行访问?我能想到的唯一理由是,如果Timer类包装一些全局系统处理,但我不明白,手柄如何参与锁定。
How can my private timer object be accessed across appdomains? The only reason I can think of is if the Timer class wraps some global system handle but I don't understand how that handle is involved in the locking.
有弱类的文档页面上的列表,但计时器没有被提及。 MemomoryStream也不在列表上,但它被包含在实施例中。如何在本地的MemoryStream对象是弱?
There is a list of weak classes on the documentation page but Timer is not mentioned. MemomoryStream is also not on the list but it is included in the examples. How can a local MemoryStream object be weak?
推荐答案
定时器
延伸的 MarshalByRefObject的
,这就是为什么它的抱怨,我怀疑。
Timer
extends MarshalByRefObject
, which is why it's complaining, I suspect.
我个人建议只锁定在其上的只有的你code可以知道的私人对象有关:
Personally I would recommend only locking on a private object which only your code can know about:
using System.Threading;
public sealed class MyClass : IDisposable {
private readonly Timer _timer;
private readonly object _mutex = new object();
public MyClass() {
_timer = new Timer(MyCallback);
}
public void SomeMethod() {
lock (_mutex) {
...
}
}
...
}
这样,你不必担心定时器
是否决定对锁定此
等等。
这篇关于不要使用System.Threading.Timer同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!