简体   繁体   English

c#为什么将对象放在lock语句中

[英]c# why put object in the lock statement

Can someone clarify me: 有人可以澄清一下吗:

The statements inside the lock will be locked no one can go through unless it's finished and release the lock. 锁中的语句将被锁定,除非完成并释放锁,否则任何人都无法通过。 then what is the object inside the lock used for 那么锁里面的对象是什么

lock (obj) 
{ 
  ///statement 
}

Does that mean the obj is being locked and cannot be used from anywhere else unless the lock has done his work. 这是否意味着obj已被锁定,除非锁定已完成工作,否则无法在其他任何地方使用obj。

I've made a very simple class to illustrate what the object in the lock is there for. 我做了一个非常简单的类来说明锁中的对象是做什么用的。

public class Account
{
    private decimal _balance = 0m;
    private object _transactionLock = new object();
    private object _saveLock = new object();

    public void Deposit(decimal amount)
    {
        lock (_transactionLock)
        {
            _balance += amount;
        }
    }

    public void Withdraw(decimal amount)
    {
        lock (_transactionLock)
        {
            _balance -= amount;
        }
    }

    public void Save()
    {
        lock (_saveLock)
        {
            File.WriteAllText(@"C:\Balance.txt", _balance.ToString());
        }
    }
}

You'll notice that I have three locks, but only two variables. 您会注意到我有三个锁,但是只有两个变量。

The lines lock (_transactionLock) mutually lock the regions of code to only allow the current thread to enter - and this could mean that the current thread can re-enter the locked region. lock (_transactionLock)lock (_transactionLock)相互锁定代码区域,仅允许当前线程进入-这可能意味着当前线程可以重新进入锁定区域。 Other threads are blocked no matter which of the lock (_transactionLock) they hit if a thread already has the lock. 如果其他线程已经拥有该锁,则无论它们碰到了哪个lock (_transactionLock)都会被阻止。

The second lock, lock (_saveLock) , is there to show you that the object in the lock statement is there to identify the lock. 第二个锁是lock (_saveLock) ,用于向您显示lock语句中的对象可以标识该锁。 So, if a thread were in one of the lock (_transactionLock) statements then there is nothing stopping a thread to enter the lock (_saveLock) block (unless another thread were already there). 因此,如果一个线程位于lock (_transactionLock)语句之一中,则没有任何事情可以阻止线程进入lock (_saveLock)块(除非已经有另一个线程存在)。

Read up on semaphores and monitors. 阅读有关信号量和监视器的信息。 When it comes to multi-threading, you want to protect the Critical Section of the code, so that the object in question is not being accessed while an operation is being performed on it. 当涉及多线程时,您希望保护代码的关键部分,以便在对其执行操作时不访问有问题的对象。 The critical section is what's being enclosed inside the lock. 关键部分是锁中包含的内容。

This is all done to avoid dead locks and live locks. 这样做都是为了避免死锁和活动锁。 Once again, you only need the lock if your application is multi-threaded. 同样,如果您的应用程序是多线程的,则仅需要该锁。

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

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