Tuesday, August 11, 2009

Lock Statement in C#.net

Lock Statement in C#.net (much usefull for bank transaction)

In .NET we can lock some object while threading once execution over and then releasing the lock.Its very usefull for bank transaction
the following example guide you to learn about Lock Statement

Syntax:

Object myLock = new Object();
lock (myLock)
{
// code section like any bank transaction
}

Explanation
Lock statement ensures that one thread does not enter a code section while another thread is in the code section. If another thread attempts to enter

a locked code, it will wait, block, until the object is released.

Example:


namespace Lock
{
class Program
{
static void Main(string[] args)
{
Thread[] threads = new Thread[10];
Account acc = new Account(1000);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.MyTransactions));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
Console.Read();
}
}

class Account
{
private Object myLock = new Object();
int Bal;

Random rnd = new Random();

public Account(int iniAmount)
{
Bal = iniAmount;
}

int Withdraw(int amt)
{

// This condition will never be true unless the lock statement
// is commented out:
if (Bal < 0)
{
throw new Exception("Negative Balance");
}

// Comment out the next line to see the effect of leaving out
// the lock keyword:
lock (myLock)
{
if (Bal >= amt)
{
Console.WriteLine("Balance before Withdrawal : " + Bal);
Console.WriteLine("Amount to Withdraw : -" + amt);
Bal = Bal - amt;
Console.WriteLine("Balance after Withdrawal : " + Bal);
return amt;
}
else
{
return 0; // transaction rejected
}
}
}

public void MyTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(rnd.Next(1, 100));
}
}
}

}

Regard

Prateek

5 comments:


  1. It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.

    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  2. I just recently discovered your blog and have now scrolled through the entire thing several times. I am very impressed and inspired by your skill and creativity, and your "style" is very much in line with mine. I hope you keep blogging and sharing your design idea

    hardware and networking training in chennai

    hardware and networking training in velachery

    xamarin training in chennai

    xamarin training in velachery

    ios training in chennai

    ios training in velachery

    iot training in chennai

    iot training in velachery

    ReplyDelete