Threading Introduction

A thread is an independent stream of instructions in a program. All your C# programs up to this point have one entry point — the Main() method. Execution starts with the fi rst statement in the Main() method and continues until that method returns.
This program structure is all very well for programs in which there is one identifi able sequence of tasks, but often a program needs to do more than one thing at the same time. Threads are important both for client – side and for server – side applications. While you type C# code in the Visual Studio editor, the code is analyzed to underline missing semicolons or other syntax errors. This is done by a background thread. The same thing is done by the spell checker in Microsoft Word. One thread is waiting for input from the user, while the other does some background research. A third thread can store the written data in an interim file, while another one downloads some additional data from the Internet.
In an application that is running on the server, one thread, the listener thread, waits for a request from a client. As soon as the request comes in, the request is forwarded to a separate worker thread, which continues the communication with the client. The listener thread immediately comes back to get the next request from the next client.
A process contains resources, such as Window handles, handles to the fi le system, or other kernel objects. Every process has virtual memory allocated. A process contains at least one thread. The operating system schedules threads. A thread has a priority, a program counter for the program location where it is actually processing, and a stack in which to store its local variables. Every thread has its own stack, but the memory for the program code and the heap are shared among all threads of a single process. This makes communication among threads of one process fast — the same virtual memory is addressed by all threads of a process. However, this also makes things diffi cult because multiple threads can change the same memory location. A process manages resources, which include virtual memory and Window handles, and contains at least one thread. A thread is required to run the program.