Summary

The .NET Framework supports multithreaded programming in two ways:

  1. By letting you explicitly create and use threads.

  2. By letting you make asynchronous calls.

Using the class Thread, you can create a thread, abort a thread, or wait for a thread to complete. You can also adjust the properties of a thread, such as the priority and the COM apartment model.

Class Thread and all other thread-related classes are defined under the namespace System.Threading.

You can use asynchronous delegates to make asynchronous calls. In this case, .NET uses threads from a thread pool to serve your request. You can use BeginInvoke to execute a method asynchronously and optionally use EndInvoke to retrieve output parameters. The asynchronous delegates work seamlessly with .NET remoting.

Asynchronous calls are also provided by the .NET Web services Framework. Use BeginXXX and EndXXX calls to begin and end a Web method.

Multithreaded programming requires careful designing. Some important issues with multithreading are shared resource conflicts, interthread communication, and performance.

To protect shared resources, the framework provides many classes, including the following:

  • Monitor: Provides exclusive access to objects.

  • Mutex: Provides exclusive access to a section of code (and therefore data).

  • ReaderWriterLock: SWMR lock.

  • Interlocked: An efficient mechanism for updating a variable.

  • MethodImpl: An attribute that synchronizes access to a method.

  • SynchronizationAttribute: An attribute that synchronizes access to all the objects in a context.

  • SyncRoot property: For synchronizing collections.

For interthread signaling, the framework provides the following classes:

  • AutoResetEvent: An event that, once raised, gets reset automatically.

  • ManualResetEvent: An event that requires explicit resetting.

  • Monitor: A portable version of event signaling.

More threads doesn't necessarily imply better performance because of the costs associated with creating a thread. Also, context switching between threads is an expensive operation.

The framework provides a thread pool and a ThreadPool class to access it. Some specific tasks can benefit from using the thread pool.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.141.6