In this code snippet, we will take a look at threads in C#.
Threads are like “small processes”. Each application runs as a process with one main thread. From there you can create new threads to execute code in parallel or better said asynchronously with respect to the main thread.
Usually, the code we write executes procedurally(line by line). So if we have a time-consuming task like writing to a file(which can be very slow compared to the speed at which things happen in the CPU) our program will have to wait for that operation to be over before continuing with its execution.
You can solve this problem by making a new child thread that will branch of the main one and run in parallel. This way the main thread can continue to run and the time-consuming operation will be executing in the child thread and not holding up the main one.
By default, threads are started as foreground threads. If you want to make a background thread you must set the IsBackground property to true before starting it. The difference between these two is that the foreground threads will keep running until they are done even if the parent thread was terminated. Meanwhile, a background thread will terminate when it’s parent thread is terminated even if they still have work to do.
Most of the time the threads don’t actually run in parallel. Each one gets to run for some time after that CPU time is given to another one. It all just happens so fast it appears as if things are running in parallel.
If you open up your task manager and look at the number of threads running you will see that you are probably running thousands of threads at once and you probably have something like 4-16 physical cores(and 8-32 virtual cores if your CPU supports hyperthreading). If we hand as many CPU cores as we have threads than all our threads could truly run in parallel. But it this case only 4-32 threads will actually run-in parallel.
Let’s have a look at the code below to see how to use threads.