简体   繁体   中英

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.

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. Other threads are blocked no matter which of the lock (_transactionLock) they hit if a thread already has the lock.

The second lock, lock (_saveLock) , is there to show you that the object in the lock statement is there to identify the 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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