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.
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!