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#.
Overview
Delve deep into the .NET threading infrastructure and use Task Parallel Library for asynchronous programming
Scale out your server applications effectively
Successfully program Windows 8 and Windows Azure asynchronous applications
In Detail
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.
What you will learn from this book
Work with raw threads, synchronize threads, and coordinate their work
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 and Windows Azure asynchronous APIs
Use Reactive Extensions to run asynchronous operations and manage their options
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:
Start Visual Studio 2012. Create a new C# Console Application project.
In the Program.cs file add the following using directives:
using System;
using System.Threading;
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);
}
}
Add the following code snippet inside the Main method:
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:
Start Visual Studio 2012. Create a new C# Console Application project.
In the Program.cs file, add the following using directives:
using System;
using System.Threading;
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);
}
}
Add the following code snippet inside the Main method:
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:
Start Visual Studio 2012. Create a new C# Console Application project.
In the Program.cs file, add the following using directives:
using System;
using System.Threading;
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);
}
}
Add the following code snippet inside the Main method:
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:
Start Visual Studio 2012. Create a new C# Console Application project.
In the Program.cs file, add the following using directives:
using System;
using System.Threading;
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);
}
}
Add the following code snippet inside the Main method:
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:
Start Visual Studio 2012. Create a new C# Console Application project.
In the Program.cs file, add the following using directives:
using System;
using System.Diagnostics;
using System.Threading;
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"));
}
}
Add the following code snippet inside the Main method: