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
Arrow up icon
GO TO TOP
Multithreading in C# 5.0 Cookbook

You're reading from   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
Product type Paperback
Published in Nov 2013
Publisher Packt
ISBN-13 9781849697644
Length 268 pages
Edition 1st 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 Task Parallel Library 5. Using C# 5.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

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.

You have been reading a chapter from
Multithreading in C# 5.0 Cookbook
Published in: Nov 2013
Publisher: Packt
ISBN-13: 9781849697644
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
Banner background image