Tuesday, 12 January 2016

                      Multi-Threading and Asynchronous                                                                 (Part 1)            

The early computers were based on batch processing .In batch processing ,a central processing unit(CPU) was capable of doing one task at a time.If a CPU has to take long time to execute a task,the other processes would have paused. In that case the whole machine would freeze.The things can be more worse,if there is a bug in the running task.The only solution is to restart the machine. The solution of this problem is Thread. In modern Operating systems each application runs in its own process. If this application affects ,the other processes would remain unaffected. Each process has its own "Virtual Memory". Each process is allowed to run for a particular time period.When this time period overs,thread is paused, it's state is saved and operating system switches to another thread.It is called "Context Switching".Actually at one time ,only one process runs on CPU. But today,as computing is so much fast and powerful and context switching happens so fast that we feel that computer is executing many tasks at a time.In .NET,for threading we use Thread Class.It can be found in System.Threading name space.

Note:Always import System.Threading in your project before using Thread Class .

Example:This is a simple example of threading.Common Mistake:When you call a function in Thread class,people commonly call it parenthesis like ().Do not call it with parenthesis.Just write down the name of the method.

Output:

















The above example shows an example of using the Thread class to run a  method . The Console class synchronizes the use of the output stream for you so you can write to it from multiple threads. Synchronization is the mechanism of ensuring that two threads don’t execute a specific portion of your program at the same time. In the case of a console application, this means that no two threads can write data to the screen at the exact same time. If one thread is working with the output stream, other threads will have to wait before it’s finished.




No comments:

Post a Comment