|< Day Day Up >|
Designing an application to perform tasks concurrently can result in an application that provides better responsiveness to a user and manages system resources more efficiently. This requires replacing the traditional synchronous approach to code execution with an asynchronous approach that uses threads. A thread is a path of execution. Each program begins running on a main thread that may create worker threads to perform tasks concurrent to its own processing.
One way to create a thread that executes a specified method is to make an asynchronous delegate invocation. This is done by creating a delegate and passing it the name of the method to be called. The delegate is then invoked with its BeginInvoke method. This causes the delegate's method to be executed on a thread that is fetched from a thread pool managed by .NET. An optional parameter to BeginInvoke is a callback method that is called when the worker thread ends. Unlike synchronous processing, in which a call to a method blocks processing in the calling method, asynchronous invocation returns control to the calling method so that it can continue processing.
Applications that require more control over a thread can create their own by passing a THReadStart or ParameterizedThreadStart delegate to the THRead constructor. A thread is executed by calling its Start method.
After the decision is made to use threads, the problem of thread-safe code must be considered. An operating system executes threads in time slices. When a thread's time expires, it is swapped out and another thread begins executing. The effects of a thread being interrupted in the middle of a task can produce unpredictable results. Thread synchronization is used to ensure that one thread has exclusive access to a code path until it completes processing. .NET provides several approaches to synchronization: an automatic approach that uses the Synchronization attribute to lock an object until a thread has finished using it; and the Mutex, Monitor, and Semaphore classes that provide a manual梑ut more granular梐pproach to implementing thread safety.
|< Day Day Up >|