Gohyu
Gohyu

Reputation: 478

ASP - How to set [lock statement] in my code?

I want to set a lock statement in my code..

I've done this so :

Set --> private static Object thisLock = new Object(); --> as global variable.

In my code:

lock (thisLock)
{
    myCode HERE...
}

I have a button click event for saving the form. Should I use this to not happen conflict with IDs. Only my code, I'll do the work? Should I write another before or after the code?

Тhank you, previously!!!

Upvotes: 0

Views: 44

Answers (1)

elviuz
elviuz

Reputation: 639

The code is fine.

Remember: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

Here a simple example from MSDN:

class Account
{
    decimal balance;
    private Object thisLock = new Object();

    public void Withdraw(decimal amount)
    {
        lock (thisLock)
        {
            if (amount > balance)
            {
                throw new Exception("Insufficient funds");
            }
            balance -= amount;
        }
    }
}

Upvotes: 1

Related Questions