Breaking News

Sunday 20 October 2013

MULTI-THREADING IN [c#]

Multi-threading :

The multi-threading  feature enable you to have more than one execution path for your application at a time. you are already aware of windows multitasking feature , which allows you to perform more then one task at the same time. In multitasking you can perform multiple task simultaneously , such as : writing an article using MS-Word , listening a song in windows media player ( WMP ) , and download a movie using Internet Download Manager. In the same way , you can use multithreding to execute different method of a program simultaneously.

for example :

MS-Word takes user input and display it on screen in one thread , while it continue to check spelling and grammatical mistakes in the second thread , and at the same time the thread save the document automatically at regular intervals.

showing the code of the multi-threading application :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace multithreading.cs
{
    class Program
    {
        static void Main(string[] args)
        {
            // creating more than one thread
            Thread FirstThread = new Thread(FirstFunction);
            Thread SecondThread = new Thread(SecondFunction);
            Thread ThirdThread = new Thread(ThirdFunction);
            Console.WriteLine("threading starting..");
            // starting more than one thread in the application
            FirstThread.Start();
            SecondThread.Start();
            ThirdThread.Start();
        }
        public static void FirstFunction()
        {
            for (int number = 1; number <= 5; number++)
            {
                Console.WriteLine(" first thread displays\t" + number);
                Thread.Sleep(2000);
            }
        }
        public static void SecondFunction()
        {
            for (int number = 1; number <= 5; number++)
            { 
                Console.WriteLine(" second thread displays\t" + number);
                Thread.Sleep(4000);
            }
        }
        public static void ThirdFunction()
        {
            for (int number = 1; number <= 5; number++)
            {
                Console.WriteLine(" third thread displays\t" + number);
                Thread.Sleep(6000);
            } Console.ReadKey();
        }
    }
}


output :






No comments:

Post a Comment

© 2013 Post by repter_x