问题描述
有这之间的区别:
内部MyClass类
{
私人只读对象_syncRoot =新的对象();
公共无效DoSomething的()
{
锁(_syncRoot)
{
:
}
}
公共无效DoSomethingElse()
{
锁(_syncRoot)
{
:
}
}
}
和这样的:
内部MyClass类
{
[MethodImpl(MethodImplOptions.Synchronized)
公共无效DoSomething的()
{
...
}
[MethodImpl(MethodImplOptions.Synchronized)
公共无效DoSomethingElse()
{
:
}
}
我看到的唯一的区别是,在一些私有成员,而第二个方法锁定在第一种方法锁该实例本身(所以应该锁定实例一切)。有没有哪种方法可以使用任何一般性的建议? 。目前我已经发现了两个教学班,在我们的项目相似的目的各有不同的方法写
编辑:
也许是一个问题。是这样的:
内部MyClass类
{
[MethodImpl(MethodImplOptions.Synchronized)]
酒店的公共无效DoSomething的()
{
:
}
}
完全一样的是这样的:
内部MyClass类
{
公共无效DoSomething的()
{
锁(本)
{
:
}
}
}
是首选第一种方法,因为你可以(也应该)做_syncRoot私人。这降低了死锁的风险。
的
MethodImplOptions.Synchronized
是一个遗留从早期雄心勃勃的想法,原来是不那么好毕竟。
关于最后一个问题:是的,根据的它们在功能上等同(但不执行方法相同)。和一切形式的锁(本)的
气馁,又因为死锁情况。
Is there any difference between this:
internal class MyClass
{
private readonly object _syncRoot = new Object();
public void DoSomething()
{
lock(_syncRoot)
{
...
}
}
public void DoSomethingElse()
{
lock(_syncRoot)
{
...
}
}
}
and this:
internal class MyClass
{
[MethodImpl(MethodImplOptions.Synchronized)]
public void DoSomething()
{
...
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void DoSomethingElse()
{
...
}
}
The only difference I see is that the first approach locks on some private member whereas the second approach locks on the instance itself (so it should lock everything else in the instance). Is there any general advice which approach to use? I have currently found two classes with similar purpose in our project each written with different approach.
Edit:
Perhaps one more question. Is this:
internal class MyClass
{
[MethodImpl(MethodImplOptions.Synchronized)]
public void DoSomething()
{
...
}
}
exactly same like this:
internal class MyClass
{
public void DoSomething()
{
lock(this)
{
...
}
}
}
The first method is preferred because you can (and should) make _syncRoot private. This lowers the risk of deadlocking.
The MethodImplOptions.Synchronized
is a left-over from an earlier ambitious idea that turned out to be not so good after all.
Regarding the last question: Yes, according to this blog they are functionally equivalent (but not implemented the same way). And all forms of lock(this)
are discouraged, again because of deadlock scenarios.
这篇关于手动锁定和同步方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!