Just had a cup of strong coffee, yes I like it that way. Less sugar, more coffee, just a perfect combination to set your mind free for receiving new ideas, and of course, serve as an energy drink to write some good posts.
Tonight I thought of writing something basic yet something very less understood, I gave it a thought for a while then I realized why not write on multithreading.
To get a jest of what we are going to talk about here, please once refer to the explanation for threading as provided in following post, and yes that shaahi paneer example, of course. So, in a nutshell, if you want to do two or more task which are either lengthy or time taking, you can do it on a different thread, keeping the main thread separate from the rest of the process.
In this part, that is part I of the post, we will see simple threading operations. As an example, here is the basic prototype of the code require to create a new thread and make it work.
1: class Program
2: {
3: static void Main(string[] args)
4: {
5: Program myProgram = new Program();
6:
7: Thread th = new Thread(myProgram.ShowThread);
8: th.Start();
9:
10: //Main thread code to be processed
11: }
12:
13: private void ShowThread()
14: {
15: //Lengthy, time consuming operation will come here.
16: }
17:
18: }
Now, let us add some code so that we can see how thread actually works.
1: class Program
2: {
3: static void Main(string[] args)
4: {
5: Program myProgram = new Program();
6:
7: Thread th = new Thread(myProgram.ShowThread);
8: th.Start();
9:
10: for (int i = 0; i<=10 ; i++)
11: {
12: Console.WriteLine("Main " + i.ToString());
13: Thread.Sleep(200);
14: }
15: Console.ReadLine();
16: }
17:
18: private void ShowThread()
19: {
20: for (int i = 0; i<=10 ; i++)
21: {
22: Console.WriteLine("Thread " + i.ToString());
23: Thread.Sleep(100);
24: }
25: }
26: }
Now as the code says, the program will create a new thread and will start processing it. Meanwhile system will print main 0 on the screen.
Next, the program is told to sleep the main thread for 200ms. So the main thread will stop for 200ms. Now the system, making use of the idle time, will start executing the second thread thus printing Thread 1 on the UI. In the second thread of course, as the code says, the system have to make Thread 2 sleep for 100ms. While the thread 2 sleeps, system will resume thread 1, if it has completed sleeping for the appropriate time, i.e. for 200ms.
And the same process will repeat on and on, thus giving result, as shown below.
What system does is, it divides the processing time within the program among different threads. To read more theory about threading please visit following post.
In the next post we will look rather deep into complex threading operations. Stay tuned.
Happy Reading!!!
0 comments