A deadlock occurs when two or more threads are trying to access the same data but are blocking each other from getting at the resources necessary to continue.

 1 internal class Program 
 2     {
 3         private static void Main( ) {
 4             Deadlocker deadlock = new Deadlocker( );
 5 
 6             Thread first = new Thread( new ThreadStart( deadlock.First ) );
 7             Thread second = new Thread( new ThreadStart( deadlock.Second ) );
 8             first.Start( );
 9             second.Start( );
10 
11             first.Join( );
12             second.Join( );
13         }
14     }
15 
16     /// <summary>
17     /// 1. First thread starts and locks resourceA
18     /// 2. Second thread starts and locks resourceB
19     /// 3. First thread blocks waiting for resourceB to be freed.
20     /// 4. Second thread blocks waiting for resourceA to be freed.
21     /// 5. The application stops in it's tracks.
22     /// </summary>
23     internal class Deadlocker {
24 
25         public void First( ) {
26             lock ( _resourceA ) {
27                 lock ( ( _resourceB ) ) {
28                     Console.WriteLine( "First" );
29                 }
30             }
31         }
32 
33         public void Second( ) {
34             lock ( _resourceB ) {
35                 lock ( ( _resourceA ) ) {
36                     Console.WriteLine( "Second" );
37                 }
38             }
39         }
40 
41         private object _resourceA = new object( );
42         private object _resourceB = new object( );
43     }

Remember that lock implicitly translates too…

 1 lock ( _resourceB ) {
 2         
 3     }
 4     
 5     // translates too
 6     Monitor.Enter( _resourceB);
 7     try {
 8         
 9     }
10     finally {
11         Monitor.Exit( _resourceB );
12     }

Instead of using Monitor.Enter(), you can use Monitor.TryEnter();

1 if ( !Monitor.TryEnter( _resourceB, TimeSpan.FromSeconds( 5 ) ) ) {
2         throw new TimeoutException( );
3     }
4     try {
5         
6     }
7     finally {
8         Monitor.Exit( _resourceB );
9     }

For more info check out…

MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework 2.0 Application Development Foundation by Tony Northrup, Shawn Wildermuth, Bill Ryan

Read more about this title…

Assignment11.zip (9.12 KB)

comments powered by Disqus