Computer programs are complex enough beasts when they are just doing one thing at a time When you start to explore the world of threads, you end up with programs that do more than one thing at once, and life can get very complicated.

There are two specific conditions that you need to be aware of when you start working
with multithreaded programs: race conditions and deadlocks.

Race Condition:
A race condition occurs when two threads "race" for access to a resource. For example, you
may have an object that's used in two threads. If one thread tries to change a value in the objec while another tries to do the same thing, a race condition can occur. You can’t guarantee which thread will get to the object first, and thus your code could end up with some nasty bugs.

To prevent this kind of thing from happening, C# has a special keyword called lock().
Lock is used to "lock" an object so that only the thread that locked it can work with it.

For an example check the snippet.

The opposite of a race condition is a deadlock. Whereas race conditions can cause your
programs to do very strange things, deadlocks can cause them to just hang and do nothing for no apparent reason.

A deadlock occurs when two threads lock each other’s resources. For example, one thread
could lock an employee object and then wait for access to a department object. A second
thread could have locked the department object and be waiting for the now locked employee
object. The net result is that both threads stop dead in the water.

There is no magic keyword to prevent deadlocks from happening. You just need to be
careful when writing your own code to make sure that you don’t end up with a situation where a deadlock can occur.

Explanation of the Snippet:
The code in the snippet locks the myEmployee object in order to increase its salary, preventing any other threads from also working with the object (perhaps to calculate the employee’s bonus or tax) until the lock block has finished.

In general, whenever you need to access an object from a thread other than the main one
(that is, a thread you created), you should lock it.

By: Touraj Ebrahimi
[toraj_e] [at] [yahoo] [dot] [com]

lock( myEmployee ) 
myEmployee.IncreaseSalary( 10 );
9 Years
Discussion Span
Last Post by Christopher_22
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.