本文介绍了递归/嵌套锁定在C#中的lock语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 可能重复:  在C#中 重入锁我在这里看着计算器和 MSDN ,并不能相信我无法找到这个问题萦绕在那里上网际网路。I've looked here on StackOverflow and on MSDN, and can't believe that I couldn't find this question lingering out there on the internets.比方说,我有一个类,我想在一些公共的方法来访问私有成员。这些公共方法将通过不同的线程,因此需要进行同步调用Let's say I have a class with a private member that I want to access in several public methods. These public methods will be called by different threads, hence the need for synchronization.public class MyClass{ private Object SomeSharedData = new Object(); public void MethodA() { lock( SomeSharedData) { // do something MethodB(); } } public void MethodB() { lock( SomeSharedData) { // do something } }}请注意该方法a和方法b可以通过这个类的用户调用,但治法还要求方法b,这导致嵌套锁定条件Note that MethodA and MethodB can be called by users of this class, but MethodA also calls MethodB, which results in a nested locking condition.难道这保证是安全的?换言之,不.NET通过引用计数锁定处理这个问题,使得当我蹦出这些方法中,锁被递减?抑或是.NET执行幕后,由此会忽略所有后续的锁在同一个线程?Is this guaranteed to be safe? In other words, does .NET handle this by reference counting the lock, so that as I pop out of these methods, the lock gets decremented? Or is .NET performing some magic behind the scenes, whereby it simply ignores all subsequent locks on the object originating from the same thread?推荐答案是的,基于锁的显示器在.NET中是递归的,并计数。Yes, locks based on Monitor in .NET are recursive, and counted.从文档的 Monitor.Enter :From the docs for Monitor.Enter:这是法律对同一线程  则启动输入不止一次没有它  堵;然而,相等数量的  退出调用之前必须调用  等待在物体上的其他线程  将解除。这是否是一件好事,或不为up辩论。Whether this is a good thing or not is up for debate. 这篇关于递归/嵌套锁定在C#中的lock语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-14 06:11