Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Multithreading in C# 5.0 Cookbook
Multithreading in C# 5.0 Cookbook

Multithreading in C# 5.0 Cookbook: Multithreaded programming can seem overwhelming but this book clarifies everything through its cookbook approach. Packed with practical tasks, it's the quick and easy way to start delving deep into the power of multithreading in C#.

Arrow left icon
Profile Icon Agafonov
Arrow right icon
Can$12.99 Can$55.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6 (5 Ratings)
eBook Nov 2013 268 pages 1st Edition
eBook
Can$12.99 Can$55.99
Paperback
Can$69.99
Subscription
Free Trial
Arrow left icon
Profile Icon Agafonov
Arrow right icon
Can$12.99 Can$55.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6 (5 Ratings)
eBook Nov 2013 268 pages 1st Edition
eBook
Can$12.99 Can$55.99
Paperback
Can$69.99
Subscription
Free Trial
eBook
Can$12.99 Can$55.99
Paperback
Can$69.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Multithreading in C# 5.0 Cookbook

Chapter 1. Threading Basics

In this chapter, we will cover the basic tasks for working with threads in C#. You will learn about:

  • Creating a thread in C#
  • Pausing a thread
  • Making a thread wait
  • Aborting a thread
  • Determining thread state
  • Thread priority
  • Foreground and background threads
  • Passing parameters to a thread
  • Locking with a C# lock keyword
  • Locking with a Monitor construct
  • Handling exceptions

Introduction

At some point of time in the past, the common computer had only one computing unit and could not execute several computing tasks simultaneously. However, operating systems could already work with multiple programs simultaneously, implementing the concept of multitasking. To prevent the possibility of one program taking control of the CPU, forever causing other applications and the operating system itself to hang, the operating systems had to split a physical computing unit across a few virtualized processors in some way and give a certain amount of computing power to each executing program. Moreover, an operating system must always have priority access to the CPU and should be able to prioritize CPU access to different programs. A thread is an implementation of this concept. It could be considered a virtual processor given to the one specific program that runs it independently.

Note

Remember that a thread consumes a significant amount of operating system resources. Trying to share one physical processor across many threads will lead to a situation where an operating system is busy just managing threads instead of running programs.

Therefore, while it was possible to enhance computer processors, making them execute more and more commands per second, working with threads was usually an operating system task. There was no sense in trying to compute some tasks in parallel on a single-core CPU because it would take more time than running those computations sequentially. However, when processors started to have more computing cores, older programs could not take advantage of this because they just used one processor core.

To use a modern processor's computing power effectively, it is very important to be able to compose a program in a way that it can use more than one computing core, which leads to organizing it as several threads communicating and synchronizing with each other.

The recipes in this chapter will focus on performing some very basic operations with threads in the C# language. We will cover a thread's lifecycle, which includes creating, suspending, making a thread wait, and aborting a thread, and then we will go through basic synchronization techniques.

Creating a thread in C#

Throughout the following recipes, we will use Visual Studio 2012 as the main tool to write multithreaded programs in C#. This recipe will show you how to create a new C# program and use threads in it.

Note

There are free Visual Studio 2012 Express editions, which can be downloaded from the Microsoft website. We will need Visual Studio 2012 Express for Windows Desktop for most of the examples and Visual Studio 2012 Express for Windows 8 for Windows 8-specific recipes.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe1.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased through your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

How to do it...

To understand how to create a new C# program and use threads in it, perform the following steps:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. Make sure that the project uses .NET Framework 4.0 or higher version.
    How to do it...
  3. In the Program.cs file add the following using directives:
    using System;
    using System.Threading;
  4. Add the following code snippet below the Main method:
    static void PrintNumbers()
    {
      Console.WriteLine("Starting...");
      for (int i = 1; i < 10; i++)
      {
        Console.WriteLine(i);
      }
    }
  5. Add the following code snippet inside the Main method:
    Thread t = new Thread(PrintNumbers);
    t.Start();
    PrintNumbers();
  6. Run the program. The output will be something like:
    How to do it...

How it works...

In steps 1 and 2 we created a simple console application in C# using .Net Framework version 4.0. Then in step 3 we included the namespace System.Threading, which contains all the types needed for the program.

Note

An instance of a program is being executed can be referred to as a process. A process consists of one or more threads. This means that when we run a program, we always have one main thread that executes the program code.

In step 4 we defined the method PrintNumbers, which will be used in both the main and newly created threads. Then in step 5, we created a thread that runs PrintNumbers. When we construct a thread, an instance of the ThreadStart or ParameterizedThreadStart delegate is passed to the constructor. The C# compiler is creating this object behind the scenes when we just type the name of the method we want to run in a different thread. Then we start a thread and run PrintNumbers in the usual manner on the main thread.

As a result, there will be two ranges of numbers from 1 to 10 randomly crossing each other. This illustrates that the PrintNumbers method runs simultaneously on the main thread and on the other thread.

Pausing a thread

This recipe will show you how to make a thread wait for some time without wasting operating system resources.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe2.

How to do it...

To understand how to make a thread wait without wasting operating system resource, perform the following steps:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. In the Program.cs file add the following using directives:
    using System;
    using System.Threading;
  3. Add the following code snippet below the Main method:
    static void PrintNumbers()
    {
      Console.WriteLine("Starting...");
      for (int i = 1; i < 10; i++)
      {
        Console.WriteLine(i);
      }
    }
    static void PrintNumbersWithDelay()
    {
      Console.WriteLine("Starting...");
      for (int i = 1; i < 10; i++)
      {
        Thread.Sleep(TimeSpan.FromSeconds(2));
        Console.WriteLine(i);
      }
    }
  4. Add the following code snippet inside the Main method:
    Thread t = new Thread(PrintNumbersWithDelay);
    t.Start();
    PrintNumbers();
  5. Run the program.

How it works...

When the program is run, it creates a thread that will execute a code in the PrintNumbersWithDelay method. Immediately after that, it runs the PrintNumbers method. The key feature here is adding the Thread.Sleep method call to a PrintNumbersWithDelay method. It causes a thread executing this code to wait a specified amount of time (two seconds in our case) before printing each number. While a thread is sleeping, it uses as little CPU time as possible. As a result, we will see that the code in the PrintNumbers method that usually runs later will be executed before the code in the PrintNumbersWithDelay method in a separate thread.

Making a thread wait

This recipe will show you how a program can wait for some computation in another thread to complete to use its result later in the code. It is not enough to use Thread.Sleep because we don't know the exact time the computation will take.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe3.

How to do it...

To understand how a program can wait for some computation in another thread to complete to use its result later, perform the following steps:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
  3. Add the following code snippet below the Main method:
    static void PrintNumbersWithDelay()
    {
      Console.WriteLine("Starting...");
      for (int i = 1; i < 10; i++)
      {
        Thread.Sleep(TimeSpan.FromSeconds(2));
        Console.WriteLine(i);
      }
    }
  4. Add the following code snippet inside the Main method:
    Console.WriteLine("Starting...");
    Thread t = new Thread(PrintNumbersWithDelay);
    t.Start();
    t.Join();
    Console.WriteLine("Thread completed");
  5. Run the program.

How it works...

When the program is run, it runs a long-running thread that prints out numbers and waits two seconds before printing each number. But in the main program, we called the t.Join method, which allows us to wait for thread t to complete. When it is complete, the main program continues to run. With the help of this technique, it is possible to synchronize execution steps between two threads. The first one waits until another one is complete and then continues to work. While the first thread is waiting, it is in a blocked state (as it is in the previous recipe when you call Thread.Sleep).

Aborting a thread

In this recipe, we will describe how to abort another thread's execution.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe4.

How to do it...

To understand how to abort another thread's execution, perform the following steps:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
  3. Add the following code snippet below the Main method:
    static void PrintNumbersWithDelay()
    {
      Console.WriteLine("Starting...");
      for (int i = 1; i < 10; i++)
      {
        Thread.Sleep(TimeSpan.FromSeconds(2));
        Console.WriteLine(i);
      }
    }
  4. Add the following code snippet inside the Main method:
    Console.WriteLine("Starting program...");
    Thread t = new Thread(PrintNumbersWithDelay);
    t.Start();
    Thread.Sleep(TimeSpan.FromSeconds(6));
    t.Abort();
    Console.WriteLine("A thread has been aborted");
    Thread t = new Thread(PrintNumbers);
    t.Start();
    PrintNumbers();
  5. Run the program.

How it works...

When the main program and a separate number-printing thread run, we wait for 6 seconds and then call a t.Abort method on a thread. This injects a ThreadAbortException method into a thread causing it to terminate. It is very dangerous, generally because this exception can happen at any point and may totally destroy the application. In addition, it is not always possible to terminate a thread with this technique. The target thread may refuse to abort by handling this exception and calling the Thread.ResetAbort method. Thus, it is not recommended that you use the Abort method to close a thread. There are different methods that are preferred, such as providing a CancellationToken method to cancel a thread execution. This approach will be described in Chapter 3, Using a Thread Pool.

Determining a thread state

This recipe will describe possible states a thread could have. It is useful to get information about whether a thread is started yet or whether it is in a blocked state. Please note that because a thread runs independently, its state could be changed at any time.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe5.

How to do it...

To understand how to determine a thread state and acquire useful information about it, perform the following steps:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
  3. Add the following code snippet below the Main method:
    static void DoNothing()
    {
      Thread.Sleep(TimeSpan.FromSeconds(2));
    }
    
    static void PrintNumbersWithStatus()
    {
      Console.WriteLine("Starting...");
      Console.WriteLine(Thread.CurrentThread
      .ThreadState.ToString());
      for (int i = 1; i < 10; i++)
      {
        Thread.Sleep(TimeSpan.FromSeconds(2));
        Console.WriteLine(i);
      }
    }
  4. Add the following code snippet inside the Main method:
    Console.WriteLine("Starting program...");
    Thread t = new Thread(PrintNumbersWithStatus);
    Thread t2 = new Thread(DoNothing);
    Console.WriteLine(t.ThreadState.ToString());
    t2.Start();
    t.Start();
    for (int i = 1; i < 30; i++)
    {
      Console.WriteLine(t.ThreadState.ToString());
    }
    Thread.Sleep(TimeSpan.FromSeconds(6));
    t.Abort();
    Console.WriteLine("A thread has been aborted");
    Console.WriteLine(t.ThreadState.ToString());
    Console.WriteLine(t2.ThreadState.ToString());
  5. Run the program.

How it works...

When the main program starts it defines two different threads; one of them will be aborted and the other runs successfully. The thread state is located in the ThreadState property of a Thread object, which is a C# enumeration. At first the thread has a ThreadState.Unstarted state. Then we run it and assume that, for the duration of 30 iterations of a cycle, the thread will change its state from ThreadState.Running to ThreadState.WaitSleepJoin.

Tip

Please note that the current Thread object is always accessible through the Thread.CurrentThread static property.

If it does not happen, just increase the number of iterations. Then we abort the first thread and see that now it has a ThreadState.Aborted state. It is also possible that the program will print out the ThreadState.AbortRequested state. This illustrates very well the complexity of synchronizing two threads. Please keep in mind that you should not use thread abortion in your programs. I've covered it here only to show the corresponding thread state.

Finally, we can see that our second thread t2 completed successfully and now has a ThreadState.Stopped state. There are several other states, but they are partly deprecated and partly not as useful as those we examined.

Thread priority

This recipe will describe the different possible options for thread priority. Setting a thread priority determines how much CPU time a thread will be given.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe6.

How to do it...

To understand the workings of thread priority, perform the following steps:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Diagnostics;
    using System.Threading;
  3. Add the following code snippet below the Main method:
    static void RunThreads()
    {
      var sample = new ThreadSample();
    
      var threadOne = new Thread(sample.CountNumbers);
      threadOne.Name = "ThreadOne";
      var threadTwo = new Thread(sample.CountNumbers);
      threadTwo.Name = "ThreadTwo";
    
      threadOne.Priority = ThreadPriority.Highest;
      threadTwo.Priority = ThreadPriority.Lowest;
      threadOne.Start();
      threadTwo.Start();
    
      Thread.Sleep(TimeSpan.FromSeconds(2));
      sample.Stop();
    }
    class ThreadSample
    {
      private bool _isStopped = false;
      public void Stop()
      {
        _isStopped = true;
      }
    
      public void CountNumbers()
      {
        long counter = 0;
    
        while (!_isStopped)
        {
          counter++;
        }
    
        Console.WriteLine("{0} with {1,11} priority " +"has a count = {2,13}", Thread.CurrentThread.Name, Thread.CurrentThread.Priority,counter.ToString("N0"));
      }
    }
  4. Add the following code snippet inside the Main method:
    Console.WriteLine("Current thread priority: {0}", Thread.CurrentThread.Priority);
    Console.WriteLine("Running on all cores available");
    RunThreads();
    Thread.Sleep(TimeSpan.FromSeconds(2));
    Console.WriteLine("Running on a single core");
    Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
    RunThreads();
  5. Run the program.

How it works...

When the main program starts, it defines two different threads. The first one, ThreadPriority.Highest, will have the highest thread priority, while the second one, that is ThreadPriority.Lowest, will have the lowest. We print out the main thread priority value and then start these two threads on all available cores. If we have more than one computing core, we should get an initial result within two seconds. The highest priority thread should calculate more iterations usually, but both values should be close. However, if there are any other programs running that load all the CPU cores, the situation could be quite different.

To simulate this situation, we set up the ProcessorAffinity option, instructing the operating system to run all our threads on a single CPU core (number one). Now the results should be very different and the calculations will take more than 2 seconds. This happens because the CPU core will run mostly the high-priority thread, giving the rest of the threads very little time.

Please note that this is an illustration of how an operating system works with thread prioritization. Usually, you should not write programs relying on this behavior.

Foreground and background threads

This recipe will describe what foreground and background threads are and how setting this option affects the program's behavior.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe7.

How to do it...

To understand the effect of foreground and background threads on a program, perform the following:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
  3. Add the following code snippet below the Main method:
    class ThreadSample
    {
      private readonly int _iterations;
    
      public ThreadSample(int iterations)
      {
        _iterations = iterations;
      }
      public void CountNumbers()
      {
        for (int i = 0; i < _iterations; i++)
        {
          Thread.Sleep(TimeSpan.FromSeconds(0.5));
          Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);
        }
      }
    }
  4. Add the following code snippet inside the Main method:
    var sampleForeground = new ThreadSample(10);
    var sampleBackground = new ThreadSample(20);
    
    var threadOne = new Thread(sampleForeground.CountNumbers);
    threadOne.Name = "ForegroundThread";
    var threadTwo = new Thread(sampleBackground.CountNumbers);
    threadTwo.Name = "BackgroundThread";
    threadTwo.IsBackground = true;
    
    threadOne.Start();
    threadTwo.Start();
  5. Run the program.

How it works...

When the main program starts it defines two different threads. By default, a thread we create explicitly is a foreground thread. To create a background thread, we manually set the IsBackground property of the threadTwo object to true. We configure these threads in a way that the first one will complete faster, and then we run the program.

After the first thread completes, the program shuts down and the background thread terminates. This is the main difference between the two: a process waits for all the foreground threads to complete before finishing the work, but if it has background threads, they just shut down.

It is also important to mention that if a program defines a foreground thread that does not complete, the main program will not end properly.

Passing parameters to a thread

This recipe will describe how to provide a code we run in another thread with the required data. We will go through the different ways to fulfill this task and review common mistakes.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe8.

How to do it...

To understand how to pass parameters to a thread, perform the following steps:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
  3. Add the following code snippet below the Main method:
    static void Count(object iterations)
    {
      CountNumbers((int)iterations);
    }
    
    static void CountNumbers(int iterations)
    {
      for (int i = 1; i <= iterations; i++)
      {
        Thread.Sleep(TimeSpan.FromSeconds(0.5));
        Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);
      }
    }
    static void PrintNumber(int number)
    {
      Console.WriteLine(number);
    }
    
    class ThreadSample
    {
      private readonly int _iterations;
    
      public ThreadSample(int iterations)
      {
        _iterations = iterations;
      }
      public void CountNumbers()
      {
        for (int i = 1; i <= _iterations; i++)
        {
          Thread.Sleep(TimeSpan.FromSeconds(0.5));
          Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);
        }
      }
    }
  4. Add the following code snippet inside the Main method:
    var sample = new ThreadSample(10);
    
    var threadOne = new Thread(sample.CountNumbers);
    threadOne.Name = "ThreadOne";
    threadOne.Start();
    threadOne.Join();
    Console.WriteLine("--------------------------");
    
    var threadTwo = new Thread(Count);
    threadTwo.Name = "ThreadTwo";
    threadTwo.Start(8);
    threadTwo.Join();
    Console.WriteLine("--------------------------");
    
    var threadThree = new Thread(() => CountNumbers(12));
    threadThree.Name = "ThreadThree";
    threadThree.Start();
    threadThree.Join();
    Console.WriteLine("--------------------------");
    
    int i = 10;
    var threadFour = new Thread(() => PrintNumber(i));
    i = 20;
    var threadFive = new Thread(() => PrintNumber(i));
    threadFour.Start(); 
    threadFive.Start();
  5. Run the program.

How it works...

When the main program starts, it first creates an object of class ThreadSample, providing it with a number of iterations. Then we start a thread with the object's method CountNumbers. This method runs in another thread, but it uses the number 10, which is the value that we passed to the object's constructor. Therefore, we just passed this number of iterations to another thread in the same indirect way.

There's more…

Another way to pass data is to use the Thread.Start method by accepting an object that can be passed to another thread. To work this way, a method that we started in another thread must accept one single parameter of type object. This option is illustrated by creating a threadTwo thread. We pass 8 as an object to the Count method, where it is cast to an integer type.

The next option involves using lambda expressions. A lambda expression defines a method that does not belong to any class. We create such a method that invokes another method with the arguments needed and start it in another thread. When we start the threadThree thread, it prints out 12 numbers, which are exactly the numbers we passed to it via the lambda expression.

Using the lambda expressions involves another C# construct named closure. When we use any local variable in a lambda expression, C# generates a class and makes this variable a property of this class. So actually, we do the same thing as in the threadOne thread, but we do not define the class ourselves; the C# compiler does this automatically.

This could lead to several problems; for example, if we use the same variable from several lambdas, they will actually share this variable value. This is illustrated by the previous example; when we start threadFour and threadFive, they will both print 20 because the variable was changed to hold the value 20 before both threads were started.

Locking with a C# lock keyword

This recipe will describe how to ensure that if one thread uses some resource, another does not simultaneously use it. We will see why this is needed and what the thread safety concept is all about.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites The source code for this recipe can be found at BookSamples\Chapter1\Recipe9.

How to do it...

To understand how to use the C# lock keyword, perform the following steps:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
  3. Add the following code snippet below the Main method:
    static void TestCounter(CounterBase c)
    {
      for (int i = 0; i < 100000; i++)
      {
        c.Increment();
        c.Decrement();
      }
    }
    
    class Counter : CounterBase
    {
      public int Count { get; private set; }
      public override void Increment()
      {
        Count++;
      }
    
      public override void Decrement()
      {
        Count--;
      }
    }
    
    class CounterWithLock : CounterBase
    {
      private readonly object _syncRoot = new Object();
    
      public int Count { get; private set; }
    
      public override void Increment()
      {
        lock (_syncRoot)
        {
          Count++;
        }
      }
    
      public override void Decrement()
      {
        lock (_syncRoot)
        {
          Count--;
        }
      }
    }
    
    abstract class CounterBase
    {
      public abstract void Increment();
      public abstract void Decrement();
    }
  4. Add the following code snippet inside the Main method:
    Console.WriteLine("Incorrect counter");
    
    var c = new Counter();
    
    var t1 = new Thread(() => TestCounter(c));
    var t2 = new Thread(() => TestCounter(c));
    var t3 = new Thread(() => TestCounter(c));
    t1.Start();
    t2.Start();
    t3.Start();
    t1.Join();
    t2.Join();
    t3.Join();
    
    Console.WriteLine("Total count: {0}",c.Count);
    Console.WriteLine("--------------------------");
    Console.WriteLine("Correct counter");
    
    var c1 = new CounterWithLock();
    
    t1 = new Thread(() => TestCounter(c1));
    t2 = new Thread(() => TestCounter(c1));
    t3 = new Thread(() => TestCounter(c1));
    t1.Start();
    t2.Start();
    t3.Start();
    t1.Join();
    t2.Join();
    t3.Join();
    Console.WriteLine("Total count: {0}", c1.Count);
  5. Run the program.

How it works...

When the main program starts, it first creates an object of the class Counter. This class defines a simple counter that can be incremented and decremented. Then we start three threads that share the same counter instance and perform an increment and decrement in a cycle. This leads to nondeterministic results. If we run the program several times, it will print out several different counter values. It could be zero, but mostly won't be.

This happens because the Counter class is not thread safe. When several threads access the counter at the same time, the first thread gets the counter value 10 and increments it to 11. Then a second thread gets the value 11 and increments it to 12. The first thread gets the counter value 12, but before a decrement happens, a second thread gets the counter value 12 as well. Then the first thread decrements 12 to 11 and saves it into the counter, and the second thread simultaneously does the same. As a result, we have two increments and only one decrement, which is obviously not right. This kind of a situation is called race condition and is a very common cause of errors in a multithreaded environment.

To make sure that this does not happen, we must ensure that while one thread works with the counter, all other threads must wait until the first one finishes the work. We can use the lock keyword to achieve this kind of behavior. If we lock an object, all the other threads that require an access to this object will be waiting in a blocked state until it is unlocked. This could be a serious performance issue and later, in Chapter 2, Thread Synchronization, we will learn more about this.

Locking with a Monitor construct

This recipe illustrates another common multithreaded error called a deadlock. Since a deadlock will cause a program to stop working, the first piece in this example is a new Monitor construct that allows us to avoid a deadlock. Then, the previously described lock keyword is used to get a deadlock.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe10.

How to do it...

To understand the multithreaded error deadlock, perform the following steps:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
  3. Add the following code snippet below the Main method:
    static void LockTooMuch(object lock1, object lock2)
    {
      lock (lock1)
      {
        Thread.Sleep(1000);
        lock (lock2);
      }
    }
  4. Add the following code snippet inside the Main method:
    object lock1 = new object();
    object lock2 = new object();
    
    new Thread(() => LockTooMuch(lock1, lock2)).Start();
    
    lock (lock2)
    {
      Thread.Sleep(1000);
      Console.WriteLine("Monitor.TryEnter allows not to get stuck, returning false after a specified timeout is elapsed");
      if (Monitor.TryEnter(lock1, TimeSpan.FromSeconds(5)))
      {
        Console.WriteLine("Acquired a protected resource succesfully");
      }
      else
      {
        Console.WriteLine("Timeout acquiring a resource!");
      }
    }
    new Thread(() => LockTooMuch(lock1, lock2)).Start();
    
    Console.WriteLine("----------------------------------");
    lock (lock2)
    {
      Console.WriteLine("This will be a deadlock!");
      Thread.Sleep(1000);
      lock (lock1)
      {
        Console.WriteLine("Acquired a protected resource succesfully");
      }
    }
  5. Run the program.

How it works...

Let's start with the LockTooMuch method. In this method, we just lock the first object, wait a second and then lock the second object. Then we start this method in another thread and try to lock the second object and then the first object from the main thread.

If we use the lock keyword like in the second part of this demo, it would be a deadlock. The first thread holds a lock on the lock1 object and waits while the lock2 object gets free; the main thread holds a lock on the lock2 object and waits for the lock1 object to become free, which in this situation will never happen.

Actually, the lock keyword is a syntactic sugar for Monitor class usage. If we were to disassemble a code with lock, we would see that it turns into the following code snippet:

bool acquiredLock = false;
try
{
  Monitor.Enter(lockObject, ref acquiredLock);

// Code that accesses resources that are protected by the lock.

}
finally
{
  if (acquiredLock)
  {
    Monitor.Exit(lockObject);
  }
}

Therefore, we can use the Monitor class directly; it has the TryEnter method, which accepts a timeout parameter and returns false if this timeout parameter expires before we can acquire the resource protected by lock.

Handling exceptions

This recipe will describe how to handle exceptions in other threads properly. It is very important to always place a try/catch block inside the thread because it is not possible to catch an exception outside a thread's code.

Getting ready

To work through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter1\Recipe11.

How to do it...

To understand the handling of exceptions in other threads, perform the following steps:

  1. Start Visual Studio 2012. Create a new C# Console Application project.
  2. In the Program.cs file add the following using directives:
    using System;
    using System.Threading;
  3. Add the following code snippet below the Main method:
    static void BadFaultyThread()
    {
      Console.WriteLine("Starting a faulty thread...");
      Thread.Sleep(TimeSpan.FromSeconds(2));
      throw new Exception("Boom!");
    }
    
    static void FaultyThread()
    {
      try
      {
        Console.WriteLine("Starting a faulty thread...");
        Thread.Sleep(TimeSpan.FromSeconds(1));
        throw new Exception("Boom!");
      }
      catch (Exception ex)
      {
        Console.WriteLine("Exception handled: {0}", ex.Message);
      }
    }
  4. Add the following code snippet inside the Main method:
    var t = new Thread(FaultyThread);
    t.Start();
    t.Join();
    
    try
    {
      t = new Thread(BadFaultyThread);
      t.Start();
    }
    catch (Exception ex)
    {
      Console.WriteLine("We won't get here!");
    }
  5. Run the program.

How it works...

When the main program starts, it defines two threads that will throw an exception. One of these threads handles exception, while the other does not. You can see that the second exception is not caught by a try/catch block around a code that starts the thread. So if you work with threads directly, the general rule is to not throw an exception from a thread, but to use a try/catch block inside a thread code instead.

In the older versions of .NET Framework (1.0 and 1.1), this behavior was different and uncaught exceptions did not force an application shutdown. It is possible to use this policy by adding an application configuration file (such as app.config) containing the following code snippet:

<configuration>
  <runtime>
    <legacyUnhandledExceptionPolicy enabled="1" />
  </runtime>
</configuration>
Left arrow icon Right arrow icon

Key benefits

  • Delve deep into the .NET threading infrastructure and use Task Parallel Library for asynchronous programming
  • Scale out your server applications effectively
  • Master C# 5.0 asynchronous operations language support

Description

In an age when computer processors are being developed to contain more and more cores, multithreading is a key factor for creating scalable, effective, and responsive applications. If you fail to do it correctly, it can lead to puzzling problems that take a huge amount of time to resolve. Therefore, having a solid understanding of multithreading is a must for the modern application developer. Multithreading in C# 5.0 Cookbook is an easy-to-understand guide to the most puzzling programming problems. This book will guide you through practical examples dedicated to various aspects of multithreading in C# on Windows and will give you a good basis of practical knowledge which you can then use to program your own scalable and reliable multithreaded applications. This book guides you through asynchronous and parallel programming from basic examples to practical, real-world solutions to complex problems. You will start from the very beginning, learning what a thread is, and then proceed to learn new concepts based on the information you get from the previous examples. After describing the basics of threading, you will be able to grasp more advanced concepts like Task Parallel Library and C# asynchronous functions. Then, we move towards parallel programming, starting with basic data structures and gradually progressing to the more advanced patterns. The book concludes with a discussion of the specifics of Windows 8 application programming, giving you a complete understanding of how Windows 8 applications are different and how to program asynchronous applications for Windows 8.

Who is this book for?

If you are a developer or new to multithreaded programming and you are looking for a quick and easy way to get started, then this book is for you. It is assumed that you have some experience in C# and .NET already, and you should also be familiar with computer science and basic algorithms and data structure

What you will learn

  • Work with raw threads, synchronize threads, and coordinate their work
  • Work effectively with a thread pool
  • Develop your own asynchronous API with Task Parallel Library
  • Use C# 5.0 asynchronous language features
  • Scale up your server application with I/O threads
  • Parallelize your LINQ queries with PLINQ
  • Use common concurrent collections
  • Apply different parallel programming patterns
  • Work with Windows 8 asynchronous APIs
  • Use Reactive Extensions to run asynchronous operations and manage their options

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 26, 2013
Length: 268 pages
Edition : 1st
Language : English
ISBN-13 : 9781849697651
Vendor :
Microsoft
Category :
Languages :
Concepts :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 26, 2013
Length: 268 pages
Edition : 1st
Language : English
ISBN-13 : 9781849697651
Vendor :
Microsoft
Category :
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 139.98
Multithreading in C# 5.0 Cookbook
Can$69.99
Learning C# by Developing Games with Unity 3D Beginner's Guide
Can$69.99
Total Can$ 139.98 Stars icon
Banner background image

Table of Contents

12 Chapters
1. Threading Basics Chevron down icon Chevron up icon
2. Thread Synchronization Chevron down icon Chevron up icon
3. Using a Thread Pool Chevron down icon Chevron up icon
4. Using Task Parallel Library Chevron down icon Chevron up icon
5. Using C# 5.0 Chevron down icon Chevron up icon
6. Using Concurrent Collections Chevron down icon Chevron up icon
7. Using PLINQ Chevron down icon Chevron up icon
8. Reactive Extensions Chevron down icon Chevron up icon
9. Using Asynchronous I/O Chevron down icon Chevron up icon
10. Parallel Programming Patterns Chevron down icon Chevron up icon
11. There's More Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(5 Ratings)
5 star 60%
4 star 40%
3 star 0%
2 star 0%
1 star 0%
Enmanuel Toribio Feb 23, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
First of all, this is a Cookbook and as such its main purpose is to serve as reference for specific usages and future needs. I wouldn't recommend reading it straight through, just use it for consulting specific things you need to do. If you do read it from start to finish though i will tell that the first few chapters introduce you to the basics of threading (which hasn't changed much since C# 2.0 as far as i know) and the complexity of the code scales in a very nice pace.All recipes follow the format of first “Getting ready” then “How to do it…” and finally “How it works…” The thing i liked the most is the “How it works…” sections since most Cookbooks don't contain a very deep explanation on how the code works but this one is less shallow than most. I won't say it explains in excruciating details every single part of the code but at least it does transmit the idea behind every code snippet well enough so you can come up with your own variations.If you are taking a degree in computer sciences or if you work with C# in a regular basis i would totally recommend to get this book into your library so you can have it for future references.
Amazon Verified review Amazon
Ryan Barrett Nov 15, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
One the better "Cookbook" style books I've read. Clear and concise examples with explanations help cut through the complexity of multithreading. I also like the overall layout of the book; going from threads, then workers, then tasks because it gives the reader an idea of the difficulties programmers faced when dealing with these various patterns and how the language evolved to alleviate these problems. I would suggest the reader to start with a more conceptual book to start with like "Parallel Programming with Microsoft.NET", but this book helped me sure up my understanding of the concepts with a lot of real world examples.
Amazon Verified review Amazon
Cyrill Kopylov Dec 19, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
All main topics are covered. There are some very cool tricks like awaiting a dynamic object and windows 8 background tasks.
Amazon Verified review Amazon
Mr. A Jul 07, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a great book to learn multithreading while practicing with the code. Each section has an example that you can use to help you learn, but I think it would have been an awesome book if the author describes the topics as well as explaining the code.For example, in section for CountDownEvent, we have code example on how to use the CountDownEvent, but there's no information about what it is and when to use it.
Amazon Verified review Amazon
J Barker Jan 18, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
It is always nice to go straight to the subject with code. A definite recommendation.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.