Sunday, 28 August 2016

Understanding Multi-Threading in C#

What is a thread???

Definition: Thread is a light weight process or it can be seen as a subset of process.

wondering what is process!!?
well process is a program which the operating system runs, in order to execute the set of instruction given to it. You may go to task manager(press ctrl+shift+del) and see large number of  processes running on the machine.
Now each process has at least one thread which is commonly called as main thread.A process can have one or more threads.

So what is Multi threading and why do we use it?

Many a times there will be a chunk of code which may take more time to execute and hence makes your application less responsive(slow). In order to prevent this we go for the concept of multi threading.

Let us understand with the help of a day to day life scenario!

"We all have been to schools,colleges or some coaching institutes or say to a place where you need take admission.
Imagine yourself sitting with a person(X) who is responsible to give you all the information about the institute, and you being a very serious candidate(just imagine ;)) ask 100s of questions . For this the person X has to be very very responsive! Or else he may loose other candidates or his manager may fire him!(sounds terrible right!,managers are always harsh!) now obviously if you have to take admission ,there is a need to fill the application form and again it is the responsibility of the institute to do so.
Now imagine person X filling the form as well as responding to our queries side by side!! what do you think what will happen? Can he be responsive with a lengthy task of filling your details!?
Not actually! So what can his manager do?? The manager may allocate another Person(Y) the job of filling your form and let Mr. X concentrate on your queries! This way both the jobs will be done smoothly.
Now imagine person X as your main process(Thread) which has a lengthy and time consuming logic of filling the form which may decrease the responsiveness of X, and now you are the manager(kind one for a change)! so you can create a new thread(Person Y) and assign the lengthy job to it so that your thread(X) is responsive as well as the task of filling the form is also completed!
This way your program will be super cool and you as a Manager will be cool dude! ;)
"

Hope it is clear!


Regards,
Ashish Agarwal

No comments:

Post a Comment