简体   繁体   English

C# 锁定语句

[英]C# Lock Statement

Im going to use the C# lock statement and im wondering if i call a function while inside a lock, and that function also does a lock on the same object will the program freeze?我将使用 C# lock 语句,我想知道我是否在锁内调用了一个函数,并且该函数也对同一个对象进行了锁定,程序会不会冻结?

For example:例如:

Object object;

public void f0()
{
   f1(object);
}

public void f1(Object obj1)
{
   lock (obj1) {
       f2(obj1);
   }
}

public void f2(Object obj2)
{
  lock(obj2) {
      /// do operations using obj2
  }
 }

Here function f0 calls function f1 which does a lock, inside that lock it calls f2 which also does a lock.这里函数 f0 调用函数 f1 来做一个锁,在那个锁里面它调用 f2 也做一个锁。 So will the program freeze in f2 waiting for the object locked in f1?那么程序会在 f2 中冻结等待锁定在 f1 中的对象吗?

I have a big program with functions calling each other passing objects around, and i need to lock some objects, but it may happen that the function i call may also lock the same object, so it may get locked twice, causing possible deadlock.我有一个大程序,函数相互调用传递对象,我需要锁定一些对象,但可能发生我调用的函数也可能锁定同一个对象,因此它可能被锁定两次,导致可能的死锁。

It may be difficult to know if the same objects gets passed around and may end up getting locked twice.可能很难知道相同的对象是否被传递并最终可能被锁定两次。

Also my program has multi-threading and multiple classes.我的程序也有多线程和多个类。

Also what if one thread gets an exception inside the lock, will it somehow unwind and fix itself?另外,如果一个线程在锁内遇到异常怎么办,它会以某种方式解除并修复自身吗?

Anybody knows the proper way to do this?有人知道这样做的正确方法吗? I have a big program so before i start changing everything i decide i better find out the proper way to do it.我有一个大程序,所以在我开始改变一切之前,我决定最好找出正确的方法来做到这一点。

Thanks谢谢

Monitor (which is used by the lock statement under the covers) is reentrant, so it's technically ok for the same thread to lock on an object multiple times. Monitor (被隐藏的lock语句使用)是可重入的,因此从技术上讲,同一个线程多次锁定一个对象是可以的。 The lock will be released when the outer lock scope completes.当外部lock作用域完成时,锁将被释放。 However, reentrant locks are difficult to reason about and should be avoided unless you have no other option.但是,可重入锁很难推理,除非您别无选择,否则应该避免使用。

Deadlocks do not occur due to reentrant locks.由于可重入锁,不会发生死锁。 They occur when you take out locks on multiple objects while some other thread locks the same objects in a different order.当您取出多个对象的锁而其他线程以不同的顺序锁定相同的对象时,就会发生这种情况。

锁定对象使其成为简单的单线程代码,可用于防止混淆或过早计算(这只是一个示例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM