O'Reilly logo

C# Essentials by Peter Drayton, Ben Albahari, Brad Merrill

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. You then start the thread and call Go, so two separate threads are running Go in parallel. However, there’s a problem: both threads share a common resource—the console. If you run ThreadTest, you get output something like this:

abcdabcdefghijklmnopqrsefghjiklmnopqrstuvwxyztuvwxyz

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 lock statement acquires ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required