Saturday, December 11, 2010

Thread life cycle in C# application

The life cycle of a thread starts when an object of the System.Threading.Thread class is created. The life cycle of The thread ends with task execution. There are various states in the life cycle of a thread.

  These states are:  
•     The Unstarted state: When an instance of the Thread class is created, the thread enters the unstarted     state. a new thread is an empty object of the thread class, and no system resources such as memory are allocated to it. You have to invoke the Start ( ) method to start the thread.

•    The Runnable state: The thread remains in the unstarted state until the program call the Start ( ) method of the Thread class, which places the thread in the Runnable state and immediately returns control to the calling thread. This state is also called as the ready or started state. The newly started thread and any other thread in the program execute concurrently. A single processor cannot execute more than one thread at a time.

•    The Not Runnable state: 
     A thread is not in the Runnable state if it is:
    1. Sleeping: A thread is put into the sleeping mode by calling the Sleep ( ) method. A sleeping thread enters the Runnable state after the specified time of sleep has elapsed.

    2. Waiting: A thread can be made to wait for some specified condition to be satisfied by calling the Wait ( ) method. The thread can be notified of the condition by invoking the Pulse ( ) method of the Thread class.

    3. Blocked: A thread could be blocked by an I/O operation. When the thread is blocked, it enters the not Runnable state.
The Dead state: A running thread enters the dead state when the statements of the thread method are complete. This state is also called the terminated state. A program can force a thread into the dead state by calling the Abort ( ) method of the Thread class on the appropriate thread object. The Abort ( ) method throws a ThreadAbortException in the thread, normally causing the thread to terminate. When a thread is in the dead state and there are no references to the thread object, the garbage collector can remove the thread object from memory.

No comments:

Recent Posts