Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Multithreading with C# Cookbook, Second Edition

You're reading from   Multithreading with C# Cookbook, Second Edition Quick answers to common problems

Arrow left icon
Product type Paperback
Published in Apr 2016
Publisher
ISBN-13 9781785881251
Length 264 pages
Edition 2nd Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Evgenii Agafonov Evgenii Agafonov
Author Profile Icon Evgenii Agafonov
Evgenii Agafonov
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Threading Basics FREE CHAPTER 2. Thread Synchronization 3. Using a Thread Pool 4. Using the Task Parallel Library 5. Using C# 6.0 6. Using Concurrent Collections 7. Using PLINQ 8. Reactive Extensions 9. Using Asynchronous I/O 10. Parallel Programming Patterns 11. There's More Index

Creating a thread in C#

Throughout the following recipes, we will use Visual Studio 2015 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

A free Visual Studio Community 2015 IDE can be downloaded from the Microsoft website and used to run the code samples.

Getting ready

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

Tip

Downloading the example code

You can download the example code files for this book from 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.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.
  • Hover the mouse pointer on the SUPPORT tab at the top.
  • Click on Code Downloads & Errata.
  • Enter the name of the book in the Search box.
  • Select the book for which you're looking to download the code files.
  • Choose from the drop-down menu where you purchased this book from.
  • Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip / UnRarX for Mac
  • 7-Zip/PeaZip for Linux

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 2015. Create a new C# console application project.
  2. Make sure that the project uses .NET Framework 4.6 or higher; however, the code in this chapter will work with previous versions.
    How to do it...
  3. In the Program.cs file, add the following using directives:
    using System;
    using System.Threading;
    using static System.Console;
  4. Add the following code snippet below the Main method:
    static void PrintNumbers()
    {
      WriteLine("Starting...");
      for (int i = 1; i < 10; i++)
      {
        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 the following screenshot:
    How to do it...

How it works...

In step 1 and 2, we created a simple console application in C# using .Net Framework version 4.0. Then, in step 3, we included the System.Threading namespace, which contains all the types needed for the program. Then, we used the using static feature from C# 6.0, which allows us to use the System.Console type's static methods without specifying the type name.

Note

An instance of a program that 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 PrintNumbers method, 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 creates 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.

You have been reading a chapter from
Multithreading with C# Cookbook, Second Edition - Second Edition
Published in: Apr 2016
Publisher:
ISBN-13: 9781785881251
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime