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 :






Read more ...

Threading In ( C# )


 Introduction :


A thread is a sequence of instruction that must be executed in a particular order to perform a specific task within a program. A program in execution is called a process and a thread can be a part of the executing program. A process executes in the Operating System ( OS ); whereas , a thread executes within a process. Therefore , a thread also called as light-weight processes. One major difference between thread and processes is that processes are fully isolated from each other. It means that the functioning of one process does not effect the functioning of another process that is running in the OS. However , thread can share memory with other thread running in the same application.

OBJECTIVES :

  • The Thread Class
  • Working With a Thread
  • Multi threading 
  • Thread priorities
  • Thread States
  • Thread Synchronization
  • Joining Thread
The Thread Class:


Name
Description
CurrentContext
Obtains the current context in which a thread is executing.
CurrentCulture
Obtains or sets the culture for a thread.
CurrentPrincipal
obtains or sets the principal for the current thread
CurrentThread
Obtain a current running thread.
CurrentUICulture
Obtains or sets a user interactive culture to a thread.
ExecutionContext
Obtain an object of ExecutionContext class that contain information of current thread.
IsAlive
Obtain a value that indicate the execution status of the current thread.
IsBackground
obtain or sets a value indicating whether or not a thread is a background thread.
IsThreadPoolThread
Obtain a value indicating whether or not a thread belongs to a thread pool
ManagedThreadID
Obtain a unique identifier for the current thread.
Name
Obtain or sets the name of the thread.
Priority
Obtain or sets a value indicating the scheduling priority of a thread.
ThreadState
Obtains a value that indicates the states of the current thread.


























Public Methods Of Thread Class:


Name
description
Abort()
Terminates the current thread and raises a ThreadAbortException exception in the thread on which its is invoked
AllocateDataSlot()
Allocate and unnamed data slot nad all the thread.
AllocateNameDataSlot()
Allocate a name data slot on all the thread.
BeingThreadAffinity()
Informs a host that the managed code is about to execute a thread that depends on the current OS.
GetData()
Retrieves a value from the current thread.
GetDomain()
Return the current domain in which the current thread running.
GetDomainID()
Return a unique application domain identifier.
GetHashCode()
Return a hash code for the current thread.
Interrupt()
Interrupts a thread that is in the WaitSleepJoin state.
Join()
Block the calling thread until an executing thread terminates.
ResetAbort()
Reset the abort operation that is requested from the current thread.
Resume()
Resume a suspended thread.
Sleep()
Block the current thread for the specified number  of milliseconds. Its an overloaded method.
Start()
Causes a thread to be scheduled for executing. Its an overloaded method.


Working With a Thread :

To enable threading in your C# programming , you need to add the system.Threading namespace , as follow ;

using System.Threading;

In this section , you learn to create , start , sleep , suspend , resume and stop a thread. Let's first learn to create a thread.

Creating a Thread :

To learn how to create a thread , you need to first create an application. Open Visual Studio and create an console application , named as MyThread. now , opent the program.cs file of MyThread application and add the following code of line as follow :

using system.threading; 

now , add the following line of code to the Main() method of the program.cs file :

Thread FirstThread = new Thread(FirstFunction);

this creates a thread as FirstThread in the MyThread application. the FirstThread thread takes a method , named as FirstFunction() , as an args. now add the following code to the program.cs file of the MyThread application to provide the definition of the FirstFunction() method.

public static void FirstFunction()
  {
     for(int number = 1; number <= 5; number++)
      {
         Console.WriteLine("first thread displays"+ number);
      }
       Console.ReadKey();
  }

now , the MyThread thread is created; however , it does not execute as it is not yet started.

starting a Thread :

till now , you have created a thread and provided definition to the FirstFunction() method but still the thread is unable to perform its task because it is not started yet. To start a thread , you need to call the Start() method of the thread class.

showing the code of MyThread application :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; // namespace required to enable threading
namespace CREATING_A_THREAD.CS
{
    class Program
    {
        public static void FirstFunction()
        {
            for (int number = 1; number <= 5; number++)
            {
                Console.WriteLine("first thread displays" + number);
            } Console.ReadKey();
        }
        static void Main(string[] args)
        {
            Thread FirstThread = new Thread(FirstFunction); // code to create a thread
            Console.WriteLine("threading starting..\n");
            FirstThread.Start(); // starting a thread
        }
    }

}

you can see that after creating the FirstThread thread  , the Start() method of the thread class is called. The FirstThread thread starts its execution after calling the Starts() method. when you run the application by pressing F5 key , the output appears , as shown in figure.

output :











Putting a Thread to Sleep :

putting a thread to sleep means to delay its execution for a certain amount of time. The Sleep() method of the thread class causes the currently executed thread to pause temporarily for the specified amount of time. The Sleep() method takes a certain amount of time ( in millisecond ) as an args , for which you want to pause a thread.

showing the code of the ThreadSleep application :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace sleep_a_thread.cs
{
    class Program
    {
        public static void FirstFunction()
        {
            for (int number = 1; number <= 5; number++)
            {
                Console.WriteLine("first thread displays" + number);
                // putting the thread on sleep for 1 second
                Thread.Sleep(1000);
            } Console.ReadKey();
        }
        static void Main(string[] args)
        {
            Thread FirstThread = new Thread(FirstFunction);
            Console.WriteLine("threading starts");
            FirstThread.Start();
        }
    }
}

the following code shows that you can pause the execution of FirstThread for 1 second by passing 1000 as an args to the Sleep() method of the thread class. when you execute the program , you will notice that there is delay of 1 second between the printing of two lines. when you run the application by pressing the F5 key , the output appears , as shown in figure.

output :







Suspending a Thread :

unlike the Sleep() method , which pauses a thread for a specific amount of time , the Suspend() method permanently pauses a thread until it is resumed by the user. it means that the  Suspend()  method causes a thread to sleep for a infinite amount of time.

showing the code of Suspend() method application :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace suspending_a_thread.cs
{
    class Program
    {
        static Thread FirstThread; // object of thread class
        public static void FirstFunction()
        {
            for (int number = 1; number <= 10; number++)
            {
                int time = new Random().Next(10, 20);
                Console.WriteLine(FirstThread.Name + "sleep for:" + time.ToString() + " millisecond");
            }
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            FirstThread = new Thread(FirstFunction);
            FirstThread.Name = "first thread";
            FirstThread.Start();
            Console.WriteLine("thread started..");
            Thread.Sleep(1000);
            FirstThread.Suspend();
            Console.WriteLine("thread suspended..");
        }
    }
}

you can see that the FirstThread thread starts its execution and the FirstFunction() method generates  a random number at every iteration , which is considered as the slept time of the thread. when the FirstThread thread reaches the total slept time of 1000 millisecond , then the program control is transferred to the Suspend() method , causing the thread to suspend for an infinite amount of time. when you execute the application by pressing the F5 key , the output appears,as shown in figure.

output :







Resuming a Thread :

To resume a suspended thread  , the thread class provides a method name as Resume().

showing the code of ResumeThread application :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace resuming_a_thread.cs
{
    class Program
    {
        static Thread FirstThread;
        public static void FirstFunction()
        {
            for (int number = 1; number <= 25; number++)
            {
                int time = new Random().Next(25, 50);
                Console.WriteLine(FirstThread.Name + "selpt for:" + time.ToString()+ "\tmillisecond");
                Thread.Sleep(2000);
            } Console.ReadKey();
        }
        
        static void Main(string[] args)
        {
            FirstThread = new Thread(FirstFunction);
            FirstThread.Name = "first thread";
            FirstThread.Start();
            Console.WriteLine("thread started..");
            Thread.Sleep(10000);
            FirstThread.Suspend();
            Console.WriteLine("thread suspended..");
            Thread.Sleep(1000);
            // code for resume a thread
            FirstThread.Resume();
            Console.WriteLine("thread resumed..");
        }
    }

}

when you run the application by pressing F5 key , the output appears , as shown in figure.

output :








Stopping a Thread :

stopping a thread means to terminate the process of its execution. The Abort() method is used to stop a thread. you should not confused the suspend() method with the abort() method ,  as the suspend method can be resumed later; however , a thread terminate by using the Abort() method cannot be resumed later. 

showing the code of the Thread Abort application :


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

namespace stopping_a_thread.cs

{

    class Program

    {

      static  Thread FirstThread;

        static void Main(string[] args)

        {

            FirstThread = new Thread(FirstFunction);

            FirstThread.Name = "first thread";
            FirstThread.Start();
            Console.WriteLine("thread started..");
            Thread.Sleep(4000);
            FirstThread.Suspend();
            Console.WriteLine("thread suspended..");
            Thread.Sleep(2000);
            FirstThread.Resume();
            Console.WriteLine("thread resumed..");
            Thread.Sleep(10000);
            FirstThread.Abort();
            Console.WriteLine("thread abort..");
            // code to stop execution of a thread
          
        }
        public static void FirstFunction()
        { 
            int number=1;
            try
            {
                for (; number <= 25; number++)
                {
                    int time = new Random().Next(25, 50);
                    Console.WriteLine(FirstThread.Name + " selpt for:\t" + time.ToString() + " millisecond");
                    Thread.Sleep(1000);
                }
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine(FirstThread.Name + "\tAborted after number\t" + number +"\titerations");
                Console.ReadKey();
            }
        }
    }
}


output :







In this post you learn ,

  • working with a thread
  • creating a thread
  • starting a thread
  • sleep a thread
  • suspending a thread
  • resuming a thread and
  • stopping a thread


Note >> Multi-threading will continue in next post ...:)
Read more ...
© 2013 Post by repter_x