Chapter 16. Threading

A C# application runs in one or more threads that effectively execute in parallel within the same application. Here is a simple multithreaded application:

using System;
using System.Threading;
class ThreadTest {
  static void Main( ) {
  Thread t = new Thread(new ThreadStart(Go));
    t.Start( );
    Go( );
  }
  static void Go( ) {
    for (char c='a'; c<='z'; c++ )
      Console.Write(c);
  }
}

In this example, a new thread object is constructed by passing it a ThreadStart delegate that wraps the method that specifies where to start execution for that thread. Then start the thread and call Go, so two separate threads are running Go in parallel. However, there’s one problem. Both threads share a common resource: the console. If you run ThreadTest, you receive output something like this:

abcdabcdefghijklmnopqrsefghijklmnopqrstuvwxyztuvwxyz

Thread Synchronization

Thread synchronization comprises techniques for ensuring that multiple threads coordinate their access to shared resources.

The lock Statement

C# provides the lock statement to ensure that only one thread at a time can access a block of code. Consider the following example:

using System;
using System.Threading;
class LockTest {
  static void Main( ) {
    LockTest lt = new LockTest ( );
    Thread t = new Thread(new ThreadStart(lt.Go));
    t.Start( );
    lt.Go( );
  }
  void Go( ) {
    lock(this)
      for ( char c='a'; c<='z'; c++)
        Console.Write(c);
  }
}

Running LockTest produces the following output:

abcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyz

The

Get C# in a Nutshell, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.