22.0 Introduction

 <  Day Day Up  >  

Using multithreaded techniques in an application can be an important way of improving responsiveness. It means, for example, that the user interface can remain active on one thread while the program is performing a lengthy database access on another thread. It also means that if the processor needs to wait while performing one task (such as retrieving some data over the network), that waiting won't cause the entire application to hang because other threads can still be doing other work. If you have a multiprocessor machine, multithreaded applications are likely to have higher performance because different threads can execute simultaneously on different processors, although you should note that on single-processor machines, this improvement does not apply.

The .NET Framework supports two means of multithreading: You can create your own additional threads explicitly, or you can ask for tasks to be performed on the Common Language Runtime (CLR) thread pool, with the CLR handling many of the details of thread management. In this chapter, we review the main programming details for both techniques. Either way, the additional threads created are normally known as worker threads. Strictly speaking, a thread is known as a worker thread if it is not running a message loop, whereas a thread executing a message loop is known as a user-interface thread, but because in practice additional created threads rarely have a message loop, we informally refer to all created threads in this chapter as worker threads. For Windows Forms applications, the main thread is a UI thread.

When using multithreaded techniques, you need to take care to synchronize access to variables across threads. If an operation to write data takes a number of machine instructions to execute, there is the possibility that the CPU will end a thread's timeslot while it is in the middle of writing data. If that happens and another thread attempts to read the data, then this thread could be reading garbage ”which leads to subtle bugs known as thread synchronization bugs. The CLR and the Windows operating system both make available objects known as thread synchronization primitives, which allow you to manage the execution of threads to prevent these bugs occurring. We also examine this topic in this chapter.

Note that to compile the code in this chapter, you need to reference the System.Threading namespace:

 
 using System.Threading; 

There is no need to reference any additional assemblies because these classes are defined in mscorlib.dll .

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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