Monday, 19 February 2018

Threading Tutorial in C# .Net - Part 1

In this lesson, we would cover the basics on threading in C# and how to implement threading in C#.

  1. Introduction to Threading
  2. The Thread Life Cycle in C#
  3. Main Thread
  4. Some Useful Properties 
  5. Some Useful Methods of a Thread
  6. Creating Threads in C#
  7. Notes on Threading

1.  Introduction to Threading
'A thread is a the smallest sequence of programmed instruction that can be managed independently' - Wikipedia.
A thread can run independently in parallel with other threads. Languages that support multithreading makes it easy to optimize the cpu time by limiting the time the CPU is idle.

2.  Thread Life Cycle
The life cycle of a thread begins when a Thread object is created and ends when the thread is completes execution or is terminated.

The life cyle of a thread in C# are the following:

Unstarted State: The instance of a thread is created but the start method have not been called

Ready State: The thread is waiting for the cpu time

Not Runnable State: When either the Sleep method is called on a thread, then the Wait method is called or when the thread is blocked by I/O  operations

Dead State: The create completes its execution or is aborted.

3.  The Main Thread
The main thread is the first thread to be executed in a C# program.
When a C# program starts running, the main thread is created automatically. The thread is created using the Thread class. Any thread created other than the main thread is called a child thread of the main thread.
A thread can be accessed using the CurrentThread property of the Thread class.

namespace ThreadingTutorial
    class Program
        static void Main()
            Thread t = new Thread(Thread2);          // Create a new thread
            t.Start();                               // Start Thread 2

            // This is the main thread executing simultaneously with Thread 2
            for (int i = 0; i < 10; i++) 
                Console.WriteLine("Main Thread");
        static void Thread2()
            for (int i = 0; i < 10; i++) Console.Write("Thread 2");

Program 1: Execution of Main Thread and Thread2 simultaneously

When the program executes, the output would be something like shown in the figure:

Figure 2: Output of execution of two threads

In Program 1, the main thread starts and creates a child thread called t. The child thread t executes a function called Thread2. Note that when when thread is created, the function to be executed is passed in as a parameter. We would explain this program a bit more to help you understand it. For now, try to enter this program in your IDE and run it to see what output you have. If you have any challenges you could leave a comment by the left of this page.

4.  Some Useful Properties of a thread
Let's now look at a some of the important properties of a thread you need to know
CurrentThread. This property gets or sets currently running thread
IsAlive: Gets the value indicating the execution status of the current thread
Name: Gets of sets the name of the thread
Priority: Gets or sets the values indicating the schedulling priority of a thread relative to other threads

5.  Some Useful Methods of a thread

public void Abort(): Calling this method terminates the thread

public void Interrupt(): Interrupts a thread that is in the WaitSleepJoin thread.

public void Join(): Blocks the calling thread untill a thread terminates. This means that you need to wait for the thread to end.

public void Start(): Start the execution of a  thread

public static void Sleep(int miliseconds): The Sleep() method pauses the current thread for a specific period of time.

public static bool Yield(): Ths causes the calling thread to yield execution to another thread that is ready to run on the current processor..

6.  Creating Threads in C#
Threads are created using the Thread class' constructor. Just like you saw in Program 1, you create a new instance of a thread and pass as argument, the function you want to be executed.
The function you pass into the thread's constructor is actually the ThreadStart delegate which indicates wheret the execution of the thread should begin.

class ThreadTest
  static void Main() 
    Thread t = new Thread (new ThreadStart (Go));
    t.Start();   // Run Go() on the new thread.
    Go();        // Simultaneously run Go() in the main thread.
  static void Go()
    Console.WriteLine ("Ndeewo nu!");

In this case, the thread t executes the Go() method, the same time the main thread calls Go(). The output would be that the string "Ndeewo nu!" is printed twice simultaneously.

But if you use the expression:

Thread t = new Thread (Go);    // No need to explicitly use ThreadStart

Then C# would determinte TheadStart delegate.We would discuss more on delegates in Part 2.

7.  Notes on Threading
Multithreading in .Net is managed by the thread scheduller. The scheduller ensures that all active threads  are alllocated execution time slots and  that the threads that are waiting or blocked does not tie down the CPU.