Tuesday, 21 August 2018

C#: Introduction to Threading

Thread is called as a light weight Process.

Each thread has its own local variables, program counter, and its life cycle independent on other threads.

Why to use Threads
a. To make the User Interface more responsive
b. To utilize the resources efficiently
c. To take the advantage of multiprocessor systems
d. To perform background processing tasks
e. To perform other operations, while one operation is waiting for I/O, or blocked etc.,

Program.cs
using System.Threading;
using System;

namespace ThreadingTutorial
{
    class HelloWorld
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(printX);
            t1.Start();

            for(int i=0; i < 100; i++)
            {
                Console.Write("Y");
            }
        }

        public static void printX()
        {
            for (int i = 0; i < 100; i++)
            {
                Console.Write("X");
            }
                
        }
    }
}
Sample Output
YYYYXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Since order of execution of threads is not predefined, you will get different results on different runs of the application.

On Sample Run1
YYYYYYXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYY

On Sample Run2
YYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXY

Thread t1 = new Thread(printX);
When main thread encounters above statement, it creates new thread and printX is the method to be executed on calling start method on Thread instance.

t1.Start();
Above statement starts the thread execution.

Can I restart the thread after its execution finishes?
No, once a thread finishes its execution, a thread cannot restart.


Previous                                                 Next                                                 Home

No comments:

Post a Comment