The benefit of using multiple threads in an application is that each thread executes asynchronously. For Windows applications, this allows time-consuming tasks to be performed in the background while the application window and controls remain responsive. For server applications, multithreading provides the ability to handle each incoming request with a different thread. Since threads are asynchronous by nature access to resources such as file handles, network connections, and memory must be coordinated. Otherwise, two or more threads could access the same resource at the same time, each unaware of the other’s actions. The result is unpredictable data corruption.
Also check out:
- Triggers in sql server 2008
- NuGet tutorial in Asp.Net
- How to Count number of times website visited and online users in asp.net using C#.net?
The lock Keyword:
The lock keyword can be used to ensure that a block of code runs to completion without interruption by other threads. This is accomplished by obtaining a mutual-exclusion lock for a given object for the duration of the code block.
A lock statement begins with the keyword lock, which is given an object as an argument, and followed by a code block that is to be executed by only one thread at a time.
using System;
using System.Threading;
class emp
{
private Object myLock = new Object();
int sal;
Random rnd = new Random();
public emp(int incentive)
{
sal = incentive;
}
int Withdraw(int amt)
{
// This condition is true only if the lock statement is commented
if (sal < 0)
{
throw new Exception("-ve Balance Amount");
}
// Comment the next line to see the effect of leaving out
// the lock keyword.
lock (myLock)
{
if (sal >= amt)
{
Console.WriteLine("salary before Withdrawal : " + sal);
Console.WriteLine("The amount to Withdraw : -" + amt);
sal = sal - amt;
Console.WriteLine("salary after Withdrawal : " + sal);
return amt;
}
else
{
return 0; // transaction is rejected
}
}
}
public void calculate()
{
for (int k = 0; k < 50; k++)
{
Withdraw(rnd.Next(1, 50));
}
}
}
class work
{
static void Main()
{
Thread[] threads = new Thread[10];
emp e1 = new emp(100);
for (int k = 0; k < 10; k++)
{
Thread t = new Thread(new ThreadStart(e1.calculate));
threads[k] = t;
}
for (int k = 0; k < 10; k++)
{
threads[k].Start();
}
}
}
The argument provided to the lock keyword must be an object based on a reference type, and is used to define the scope of the lock. It is good practice to avoid locking on a public type, or on object instances beyond the control of your application. For example, lock(this) can be problematic if the instance can be accessed publicly, because code beyond your control may lock on the object as well. This could create deadlock situations where two or more threads wait for the release of the same object. it is best to lock a private or protected member that is not interned.
Monitors
Like the lock keyword, monitors prevent blocks of code from simultaneous execution by multiple threads. The Enter method allows one and only one thread to proceed into the following statements; all other threads are blocked until the executing thread calls Exit. This is just like using the lock keyword. In fact, the lock keyword is implemented with the Monitor class. For example:
lock (xyz)
{
DoSomething();
}
This is equivalent to:
System.Object obj = (System.Object)xyz;
System.Threading.Monitor.Enter(obj);
try
{
DoSomething();
}
finally
{
System.Threading.Monitor.Exit(obj);
}
Using the lock keyword is generally preferred than the Monitor class directly,since lock is more concise, and it insures that the underlying monitor is released, even if the protected code throws an exception. This is accomplished with the finally keyword, which executes its associated code block regardless of whether an exception is thrown.
Also check out:
- Triggers in sql server 2008
- NuGet tutorial in Asp.Net
- How to Count number of times website visited and online users in asp.net using C#.net?
The lock Keyword:
The lock keyword can be used to ensure that a block of code runs to completion without interruption by other threads. This is accomplished by obtaining a mutual-exclusion lock for a given object for the duration of the code block.
A lock statement begins with the keyword lock, which is given an object as an argument, and followed by a code block that is to be executed by only one thread at a time.
using System;
using System.Threading;
class emp
{
private Object myLock = new Object();
int sal;
Random rnd = new Random();
public emp(int incentive)
{
sal = incentive;
}
int Withdraw(int amt)
{
// This condition is true only if the lock statement is commented
if (sal < 0)
{
throw new Exception("-ve Balance Amount");
}
// Comment the next line to see the effect of leaving out
// the lock keyword.
lock (myLock)
{
if (sal >= amt)
{
Console.WriteLine("salary before Withdrawal : " + sal);
Console.WriteLine("The amount to Withdraw : -" + amt);
sal = sal - amt;
Console.WriteLine("salary after Withdrawal : " + sal);
return amt;
}
else
{
return 0; // transaction is rejected
}
}
}
public void calculate()
{
for (int k = 0; k < 50; k++)
{
Withdraw(rnd.Next(1, 50));
}
}
}
class work
{
static void Main()
{
Thread[] threads = new Thread[10];
emp e1 = new emp(100);
for (int k = 0; k < 10; k++)
{
Thread t = new Thread(new ThreadStart(e1.calculate));
threads[k] = t;
}
for (int k = 0; k < 10; k++)
{
threads[k].Start();
}
}
}
The argument provided to the lock keyword must be an object based on a reference type, and is used to define the scope of the lock. It is good practice to avoid locking on a public type, or on object instances beyond the control of your application. For example, lock(this) can be problematic if the instance can be accessed publicly, because code beyond your control may lock on the object as well. This could create deadlock situations where two or more threads wait for the release of the same object. it is best to lock a private or protected member that is not interned.
Monitors
Like the lock keyword, monitors prevent blocks of code from simultaneous execution by multiple threads. The Enter method allows one and only one thread to proceed into the following statements; all other threads are blocked until the executing thread calls Exit. This is just like using the lock keyword. In fact, the lock keyword is implemented with the Monitor class. For example:
lock (xyz)
{
DoSomething();
}
This is equivalent to:
System.Object obj = (System.Object)xyz;
System.Threading.Monitor.Enter(obj);
try
{
DoSomething();
}
finally
{
System.Threading.Monitor.Exit(obj);
}
Using the lock keyword is generally preferred than the Monitor class directly,since lock is more concise, and it insures that the underlying monitor is released, even if the protected code throws an exception. This is accomplished with the finally keyword, which executes its associated code block regardless of whether an exception is thrown.