|< Day Day Up >|
Topics in This Chapter
An application or component can be designed to operate in a synchronous or asynchronous manner. In the synchronous model, tasks are performed in sequence as in a relay race, one runner (task) must complete his segment before the next one can start. In contrast, asynchronous programming permits an application to be broken into subtasks that perform concurrently. This approach (sometimes referred to as send and forget) allows one method to call another method and then continue processing without waiting for the called method to finish.
The key to asynchronous programming is the use of threads. A thread is essentially a code sequence that runs independently. This permits a program to work on multiple tasks in a parallel manner. For example, an application may use one thread to accept user input to a form, while a second thread concurrently processes a print request. When used judiciously, threads can greatly improve a program's performance and responsiveness; when used incorrectly, they can cause programs to hang or terminate without properly completing a task.
A thread is created and run by the operating system not by .NET. What .NET does is create a wrapper around a thread so that it obeys the rules of the .NET managed environment. An asynchronous application may work indirectly or directly with threads. In the former case, delegates are used to automatically allocate and handle threads; in the latter case, a program explicitly creates instances of the Thread class and takes responsibility for synchronizing thread behavior.
The chapter begins with an overview of threads and then looks at asynchronous programming using both delegates and explicit thread creation. The final section examines the synchronization issues that arise when multiple threads are running, and introduces several synchronization techniques that can be used to enable threads to share resources.
|< Day Day Up >|