Basics Of Threading In C#

Introduction

This blog presents a basic understanding of threads, the process, and its advantages and disadvantages.

  • Process
    Process is what the OS uses to facilitate the execution of a program by providing the required resource. Each process has a unique process Id associated with it. You can view a process within which a program is being executed in Window task manager.

  • Thread
    Thread is a lightweight process. A process has at least one thread, which is commonly called the main thread. A single process can have multiple threads.

All the threading related classes are present in System.Threading namespace.

Advantages and disadvantages of Multithreading

Advantages

  1. To maintain a responsive user interface.
  2. To make an efficient use of processor time, while waiting I/O operation to complete.
  3. To split large CPU- bound task to be processed simultaneously on a machine, which has multiple processors/cores. Different processors execute different thread simultaneously, so performance improves.

Disadvantages:

  1. If the machine is single processor/cores, then the multithreading causes the overhead over the processor, as it is using context switching. Context switching means the division of single processor time to the multiple threads, while switching time from one thread to other may also consume some time. Hence, overall performance is affected adversely.

  2. Obviously, you have to write more lines of code. Multithreaded Applications are difficult to write, understand, debug and maintain.

Hence, only use multithreads, if the advantages are greater than the disadvantages.