DEV Community

Cover image for Manage program flow in .NET #1 – Understand how threads and context switching work
PTKhuong96
PTKhuong96

Posted on

Manage program flow in .NET #1 – Understand how threads and context switching work

Here is the first post in the series: Manage program flow in .NET! In this series, I will step by step to share my knowledge on managing program flow in the .NET applications.

Threads – What and Why?
Imagine that every computer has only one CPU which is capable of executing the only operating at a time.

Your machines will be unresponsive or get freeze if many tasks are in the queue – For example, you have to stop youtube before switching to MS PowerPoint to prepare for your presentation slide tomorrow (just so boring for me).

Also, imagine what would happen if the CPU has to work overload to execute a long-task, the happy case is it will be completed successfully. But in case there a bug during executing, your system would get stuck. Then please, restart your machine, that is the only way to deal with it 🙂

Luckily, the concept: Threading was born to solve the problem!

a thread is something like a virtualized CPU for each process.

Each application runs in its own process under a thread, each process is isolated from the others. This is to make sure that the failure of a single one will not impact the others.

CPU’s Context switching
Most of the computer comes with one or multiple CPUs (the case of server machines), each CPU come with multiple cores. To make use of all the cores of a CPU, it should be run into a multithreading scheme.

each thread is allowed by Windows to run for a certain time period. after this period ends, the current thread is paused and Windows switch to another thread. This is called: Context switching.

Context switching ensures that threads can do their own jobs without having to wait for others to complete.

Obviously, there is also some work that must take by Windows for switching between threads. Especially, it needs to make sure the whole context of the current thread is saved and restored without any issue on each switch.

Overall, it is extremely great to improve the responsiveness of the systems, end-users will feel like their computers can do so many works at the same time.

And more…
That is enough of knowledge for developers having a glance on the multithreading from OS’s aspect. On the next posts, we will step by step deep dive into how we can deal with multithreading in .NET and C#. Be a follower! 😉

Happy coding again !

Top comments (0)