.NET
  Home arrow .NET arrow Page 13 - Threading in Delphi for .NET
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
.NET

Threading in Delphi for .NET
By: Xavier Pacheco
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 8
    2004-08-30

    Table of Contents:
  • Threading in Delphi for .NET
  • Threading
  • The System.Threading Namespace
  • Delegates in Delphi
  • Creating Threads Using Static Methods
  • Threading Priority
  • Apartment State and Thread Pooling Class
  • Timer Classes
  • Writing Thread-safe Code .NET Style
  • Mutex and Monitor Classes
  • Locks that Distinguish Between Readers and Writers
  • Events
  • Thread Local Storage
  • User Interface Issues
  • Threading Exceptions

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Threading in Delphi for .NET - Thread Local Storage


    (Page 13 of 15 )

    Using variables that are global in a multithreaded application is a surefire way to cause debugging nightmares. Unless these global variables are protected, sleepless nights are guaranteed.

    Sometimes it is necessary to have a variable that is global to a thread. Thread Local Storage is the name given to variables that are global to a specific thread. The easiest way to create this kind of variable is to use the threadvar keyword. Although they are declared like a standard unit global variable, each thread is allocated a separate slot for storing the contents of the variable.

    Initialization of threadvars is not allowed. Each thread needs to initialize the variable before using it. An example of a threadvar looks like

    threadvar
    MyThreadVariable: integer; // remember, no initialization

    In the .NET Framework, the System.Threading.Thread class has two methods for creating thread local storage. They are the AllocateDataSlot() and the AllocateNamedDataSlot() methods. Finally, use the ThreadStaticAttribute to create a static field unique for each thread. Delphi for .NET currently maps threadvars with the [ThreadStatic] attribute.

    Take extra caution when using thread local storage with any mechanism that uses threads from the ThreadPool. Another thread might or might not have already initialized a thread local variable with an unexpected value.

    Win32 Interprocess Communications

    The Win32 API has more IPC mechanisms available that have not been ported to the managed world. Named pipes and semaphores can be leveraged by using Platform Invoke (PInvoke). This may be the best option when integration is needed with existing Win32 applications. Be wary of performance issues, however, because PInvoke has associated overhead costs. PInvoke is covered in Chapter 16, "Interoperability: COM Interop and the Platform Invocation Service."

    Thread-safe .NET Framework Classes and Methods

    Thread safety is a serious issue when writing multithreaded applications. So how can one determine if a particular method or class is thread-safe?

    When it comes to thread safety in the .NET Framework, one thing is guaranteed: All methods that are public class (static) methods are thread-safe, as long as they only refer to their parameters. This makes sense because class methods cannot refer to any instance data. In general, all other methods are not thread-safe unless the SDK documentation clearly states otherwise.

    The Synchronized() Method

    Most collection classes have helper properties and methods. A thread-safe queue is obtained by using the following code:

    myThreadSafeQueue = System.Collections.Queue.Synchronized(
      System.Collections.Queue.Create);

    All access to the synchronized queue is now thread-safe. Be aware that a thread-safe collection will be approximately two times slower than an unsynchronized collection.

    The IsSynchronized and SyncRoot Properties

    Collections that support the Synchronized() method also have a property that indicates if the collection is in fact synchronized. Use the IsSynchronized property to determine if the collection is synchronized.

    Another method of making a collection thread-safe is to use a System.Threading.Monitor. Recall that a Monitor requires an object to perform the locking. This object must be the object returned by collection's SyncRoot property.

    Be sure to look for the IsSynchronized and SyncRoot properties on other classes within the .NET Framework—specifically, those classes that implement the ICollection interface. For example, the System.Array class is one class that implements these properties as well. Arrays are not thread-safe, and the IsSynchronized returns false. Serialize access to the array by locking on the SyncRoot property of the array.


    Caution - Classes that contain the SyncRoot property require due diligence on the part of the developer to ensure that every access to the array is locked before iterating or indexing its members. Nothing within the .NET Framework prevents one thread from properly locking an instance and another from using the same instance, bypassing any locking mechanism. A better alternative is to write a thread-safe class that encapsulates the appropriate storage mechanism and guarantees that all accesses to the internal class are locked.


    This chapter is from Delphi for .NET Developer's Guide, by Xavier Pacheco (Sams, 2004, ISBN: 0-672-32443-1). Check it out at your favorite bookstore today.

    Buy this book now.

    More .NET Articles
    More By Xavier Pacheco


     

    .NET ARTICLES

    - Using CrystalReportViewer to Display Crystal...
    - Creating Summary .Net Crystal Reports
    - More on Commands, Input and the WPF
    - Grouping and Aggregating When Querying LINQ ...
    - Commands, Input and the WPF
    - Keyboard and Ink Input with WPF
    - Mouse Input and the WPF
    - Input with Windows Presentation Foundation
    - Introducing LINQ with XML and Databases
    - An Introduction to LINQ
    - Querying LINQ to SQL: Basics
    - Completing a Simple Storefront with LINQ
    - Knowing Your Environment: the System.Environ...
    - Creating the Home Page for a Simple Storefro...
    - LINQ Quickly with Language Integrated Queries

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT