Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 697
LittleFunny Avatar asked Jun 15 '16 04:06

LittleFunny


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C language?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


1 Answers

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).

like image 117
Enigmativity Avatar answered Sep 26 '22 13:09

Enigmativity