Multithreading In C#

If we run an application having 3 methods, by default it will run in a default single thread, one after the other.

The drawback is when there is some issue or delay with the 1st method, it will stop until it is completed and Method 2,3 is not executed until method 1 is completed.

  • To overcome this we can use the concept of Multi-threading, here we can have more than 1 thread and each method is part of the separate thread and given equal importance and time is shared. "Time sharing"

    Advantage: max utilization of CPU

    Make a note: execution is not parallel.

    Rather OS gives an equal slot of time (say: 2sec) to each thread to exec. and then again goes back repeat the cycle. Here we don't need to wait if a method is taking too long to execute,

  • Note that in multi-threading the priority in which the methods will execute is not in our control by default. For the above, we took into consideration that t1 > t2 > t3 will execute in this order.
  • Observation: both of the approaches took 12 seconds to complete the task, so what's the advantage? You can see clearly in multi-threading that  test 2 and test 3 didn't wait for test 1 to complete which was taking more time. Hence using multi-threading CPU shares time slots for threads to execute.