Thursday, December 9, 2010

How to Manage threads in c# Console Application.

There are many tasks you might need to perform to manage the activity or life of a thread. You can manage all these tasks by using the various thread methods available with the Thread class.
For example, when you require the thread to pause for a period of time so that the thread is allowed to execute, you can  use the Thread.Sleep ( ) method. This method takes a single argument that represents time in milliseconds for which you want the thread to pause. This method is a static method and cannot be called with an instance of a thread object. This is done to avoid a call to the Thread.Sleep ( ) method on any other thread except the currently executing method. The static Thread.Sleep ( ) method call the static CurrentThread method, which then pauses that thread for the specified amount of time.

The following example shows the implementation of the Sleep ( ) method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadSample
{
    class BasicThreadApp
    {
      public  static void ChildThreadCall()

        {
            Console.WriteLine("Child thread started");
            int SleepTime = 5000;
            Console.WriteLine("Sleeping for {0} Second", SleepTime / 1000);
            Thread.Sleep(SleepTime); // Sleep for five second.
            Console.WriteLine("Waking up");
      }
        public static void Main()
        {
            ThreadStart ChildRef = new ThreadStart(ChildThreadCall);

            Console.WriteLine("Main - Creating child thread");

            Thread ChildThread = new Thread(ChildRef);
            ChildThread.Start();

            Console.WriteLine("Main - Have Requsted the start of child thread");
            Console.ReadLine();
        }
    }
}

Output is shows below.



Note: - There is more than one way to call the Sleep( ) method. One way is to call Thread.Sleep  ( ) with a value 0, which will cause the current thread to hand over the unused balance of its timeslice. The other way is to call Thread.Sleep ( ) method with a value of Timeout. Infinite, which result in the thread begin paused indefinitely until it is interrupted by another thread calling the suspended thread’s Thread. Interrupt ( ) method.



What Other's are reading.
Identifying the Thread priority in console application.
Creating multiple threads in console Application.
Understanding Advantages and limitations of multithreading in Console Application.
How to Set the Thread priority in C#.

No comments:

Recent Posts