Checking whether the current thread owns a lock

后端 未结 10 650
攒了一身酷
攒了一身酷 2021-02-02 13:32

Suppose I have the following code:

public class SomeClass()
{
    private readonly object _lock = new object();

    public void SomeMethodA()
    {
        lock         


        
10条回答
  •  无人共我
    2021-02-02 14:10

    Locking or re-locking are effectively free. The downside of this low cost is that you don't have as many features as the other synchronisation mechanisms. I would simply lock whenever a lock is vital, as you have above.

    If you desparately want to omit 'unnecessary' locks without the risk involved with potential refactoring, add comments. If someone changes your code and it breaks, there is a comment there that explains why. If they still can't figure it out, that's their problem, not yours. A further alternative is to create a class for use as a locking object that contains a boolean you can flick on and off. However, the overheads introduced by doing this (including try/finally blocks, which are not free), are probably not worth it.

提交回复
热议问题