C# Code for Parallel Execution

What is thread? 

Program blocks are made of bunch of statements. These statements inside the program blocks are executed generally one after the other. With threads it is possible to execute 2 or more program blocks parallelly.

As a programmer, it's important to grasp the benefits threads offer. Delving into their functionality and implementation details can be a topic for another time.

Need for threads

Consider a web server, now to serve a web request there would be a block of code. Executing this block of code will serve on request. In a web server, we cannot serve one request after the other especially in scenarios where time taken to serve a web request is significant. Threads come in handy to solve this problem. Most web servers serve different web request using different threads.

Code Example

The below code snippet shows how to create a thread that will write * to console every 100 ms. While the mail thread will write # to the console at interval of 120 ms.

#####

Output




When program blocks gets executed in parallel by multiple threads, there could be potential time saving. Multi-threading is used internally in web servers like ASP. Net Core to cater to multiple requests by using different threads for different requests

With multi-threading, you can have certain tasks get executed in the background while addressing other tasks in the foreground. 

Here in this program, two simulated reads from two different systems are done in parallel as can be noted from output console


                                                                      C# Code 




                                                                Sample of Output

 












Comments