本文介绍了使用私有变量锁定 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据埃里克·冈纳森的说法

according to Eric Gunnerson

不要

  • 使用锁(这个)
  • 使用锁(typeof())

做锁定私有变量,而不是用户可以看到的东西如果您需要私钥来锁定,请使用object key = new object()"

DoLock on a private variable, not on something the user can seeUse "object key = new object()" if you need a private key to lock on

是什么原因??

推荐答案

因为任何不是私有的东西都意味着可以从外部用于锁定其他人或某些不受您控制的代码,从而导致死锁.

Because anything that is not private means that could be used from the outside to lock on by someone else or some code that is outside from your control leading to deadlocks.

最佳做法是锁定私有静态变量,如下所示:

The best practice is to lock on private static variables, like this:

private static object _syncRoot = new object();

然后:

lock(_syncRoot)
{
    ...
}

私有实例变量也可能是危险的,因为你的类的实例不是你作为类的实现者拥有的东西.它是拥有该实例的类的消费者.

private instance variables could also be dangerous since the instance of your class is not something that you as implementer of the class own. It's the consumer of the class that owns the instance.

这篇关于使用私有变量锁定 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:12
查看更多