13.5. Summary

 < 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 but more granular approach to implementing thread safety.

     < Day Day Up > 


    Core C# and  .NET
    Core C# and .NET
    ISBN: 131472275
    EAN: N/A
    Year: 2005
    Pages: 219

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net