Thread


Introduction to Threads in C#

Towards the end of the 20th century, computers could already work with several programs simultaneously. This is normally called multitasking.

However, only one computing unit had to be executed at a given time. So the risk was that one program could monoplize the CPU, causing other applications and the Operating System itself to wait for ever.

So the Operating System designers decided to split a physical unit across a few virtualized processors in some way. This could then give a certain amount of processor time to each executing program.

Besides, the Operating System had to be given higher priority to the processor time. Then the Operating System could prioritize the CPU access across different programs.

This implementation is what we call a thread.

A thread is a path of execution that exists within a process. Threads are like virtual processors assigned to a specific programs. The program then runs the thread independently.

A process is an instance of the program that is being executed.A process can comprise one or more threads.

Processors were becoming faster and faster, being able to execute more instructions per second.

But later on, modern processors started to have more computing cores, instead of becoming faster. However, programs written in the older way could not take advantage of this increase in power via multiple cores since they were designed to run on a single core processor.

So nowadays it is important to write programs that can use more than one computing core. This allows them to effectively utilize the modern processors power.

To achieve this we can execute tasks using multiple threads. The threads should then be able to properly communicate and synchronize with each other.

Creating a Thread

The Thread class is defined in the System.Threading namespace.

using System.Threading;

Let's look at an example of creating a thread that prints out stars defined in an array. In fact we have two arrays: one stars array and the other nebulas array.

The stars array will be creating and rendered from our background thread while the nebulas array will be created and printed out from main thread.

using System;
using System.Threading;

namespace MsThread
{
    class Program
    {
        static void Main()
        {
            Thread t = new Thread(showStars);
            t.Start();
            showNebulas();
            Console.ReadLine();

        }
        static void showNebulas()
        {
            Console.WriteLine("Main Thread...................");
            string[] nebulas = {"Horse Head","Ghost Head","Orion","Pelican","Witch Head","Helix","Boomerang","Bernad 68"};
            foreach (var nebula in nebulas)
            {
                Console.WriteLine(nebula);
            }
            Console.WriteLine();

        }
        static void showStars()
        {
            Console.WriteLine("Starting Stars Thread.............");
            string[] nebulas = { "UY Scuti", "VY Canis Majoris", "VV Cephei A","NML Cygni", "Betelgeuse","Antares","Rigel","Aldebaran" };
            foreach (var nebula in nebulas)
            {
                Console.WriteLine(nebula);
            }
        }
    }
}

Result

Main Thread...................
Horse Head
Ghost Head
Orion
Pelican
Witch Head
Helix
Boomerang
Bernad 68

Starting Stars Thread.............
UY Scuti
VY Canis Majoris
VV Cephei A
NML Cygni
Betelgeuse
Antares
Rigel
Aldebaran

We create a thread by instantiating the System.Threading.Thread class.

Then we pass an instance of ThreadStart or ParameterizedThreadStart delegate via the constructor.

The C# compiler will then create an object behind the scenes as long as we pass the name of the method we want to run in the different thread.

To start the thread we use the start() method.

The showNebulas() on the other hand will be run in the main thread.

Best Regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post