Saturday, December 12, 2015

Multi-threaded programming

We will see how to use the multi-threaded programming in C#. See here to see what the multi-threading is.

the code:
using System;
using System.Threading;

namespace ThreadTest
{
    class Program
    {
        public static void Main() {
                Thread thrd1 = new Thread(new ThreadStart(MyThread.Thread1 ) );
                Thread thrd2 = new Thread(new ThreadStart(MyThread.Thread2 ) );

                thrd1.Start();
                thrd2.Start();
              
                Console.ReadKey(true);
        }
    }
  
    public class MyThread {

        public static void Thread1() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread1 {0}", i);
                }
        }

        public static void Thread2() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread2 {0}", i);
                }
        }
    }
}

To use the multi-threading, you have to make an object of class Thread. In this program, "thrd1" and "thrd2" are the objects that we have made. After making such thread's object, ".Start()" is used to start the thread. In this program, "thrd1.Start();" and "thrd2.Start()" are written to start the threads that we have made.

the result

The each thread works independently, so the result above shows the two threads that we have made are working simultaneously.

In the first program, the thread function (of MyThread class) was static function. But the thread function doesn't need to be static. If we will NOT use the thread function as static, we must make an object of Thread class and use it as follows:

using System;
using System.Threading;

namespace ThreadTest
{
    class Program
    {
        public static void Main() {
                MyThread thrdobj = new MyThread();
          
                Thread thrd1 = new Thread(new ThreadStart(thrdobj.Thread1 ) );
                Thread thrd2 = new Thread(new ThreadStart(thrdobj.Thread2 ) );

                thrd1.Start();
                thrd2.Start();
              
                Console.ReadKey(true);
        }
    }
  
    public class MyThread {

        public void Thread1() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread1 {0}", i);
                }
        }

        public void Thread2() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread2 {0}", i);
                }
        }
    }
}

References

"Multithreaded Programming Using C#", Code project, seen on 12th December 2015