Saturday, December 4, 2010

Understanding how to create Threads in console application.

You can create threads by extending the thread class. The extended Thread class calls the Start ( ) method to begin the child thread execution.

Example:


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 atarted");
        }
        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 requested the start of child thread");
            Console.ReadLine();
  
    }

    }
}

Output is display below:
 Main - creating Child thread
Main - Have requested the start of child thread
Child thread started

Note: - The Main ( ) method prints before the message from the child thread, proving that the child thread is indeed working asynchronously.
The first using statement for the System.Threading namespace. The first statement of the Main ( ) method specifies the method to be invoked by the thread:
    ThreadStart ChildRef  =  new ThreadStart(ChildThreadCall)
The next statement instantiates a Thread object where the constructor takes the object of the ThreadStart class as its argument:
Thread ChildThread = new Thread(ChildRef);
 Then, the start ( ) method of the Thread object is called, and the method results in a call to the ChildRhreadCall method. The extended Thread class calls the Start( ) method to begin the child thread execution.

No comments:

Recent Posts