Multithreading

Imagine you need to write a program with a method that takes ages to execute, if you create this in procedural way, the console will freeze and user will be unable to do anything.  This problem can be solved by using multiple cores of processor unit. Assign long task to a single core other than the main one.

Today I’ll demonstrate a simple example of multi-threading process to show you how to deal with this type of situations.

Lets analyse simple example

using System;
//Multi Threading is a part of System.Threading library.  
using System.Threading;

public class Test
{
    static void Main()
    {
      
        Thread thread = new Thread(TaskMethod);
        thread.Start(); // kicks new tread
        
        for (int i=0; i < 5; i++)  //kicks another thread
        {
            Console.WriteLine ("Main thread: {0}", i);
            Thread.Sleep(1000);   //sleep 1s
        }
    }
    
    static void TaskMethod()
    {
        for (int i=0; i < 10; i++)
        {
            Console.WriteLine ("Other thread: {0}", i);
            Thread.Sleep(500); //sleep 0.5s
        }
    }
}

This example demonstrates the outcome of two simultaneous threads. We invoke our thread in main function and in the next line we start another similar task, running at the same time. Lets take a look at the console output.

Thread

We can see that as we expected both loops are running together without any delay.

Recap:

  • Threads can be declared by passing function into it.Function name does not contains parenthesis.
Thread thread = new Thread(TaskMethod);
  • Thread is executed by threat.Start() method
  • All thread related methods are inside System.Threading library.

This concept involves technical knowledge of CPU but implementation of treads is not that difficult, now when you know the basics, we can move to real world examples. In next part I’ll show you how to deal with an situation I presented in first paragraph.Stay Awesome!

Welcome

First of all, little bit about myself. I’m self taught software developer. My main language is c# and for my projects im using mainly .NET framework and Unity Engine.

Short biography. After doping out from University(Undergraduate in robotics) and over year of searching for place for myself I decided to go back to Software Development. I graduated from college in UK , after seeing the level of education here I decided to become a developer without help of university. I’ll share with you knowledge i gained over years of searching and self development, finishing lots of Massive Open Online Courses, education in different countries and  on different levels.

This blog is about software development and technology. I’ll post helpful tips and information that can be useful for software developers, game developers, and people  interested in technology. I’ll try to cover basic and more advanced topics.