.NET
  Home arrow .NET arrow Page 7 - 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 
Moblin 
JMSL Numerical Library 
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 - Apartment State and Thread Pooling Class


    (Page 7 of 15 )

    System.Threading.ApartmentState Enumeration

    The .NET Framework creates an apartment when it interacts with COM objects. This apartment is specified in one of two ways. For manually created threads, the ApartmentState property can be set to the appropriate ApartmentState enumeration. These values are listed in Table 14.3.

    Table 14.3 Values of the System.Threading.ApartmentState Enumeration

    Value

    Description

    STA

    Single-threaded apartment

    MTA

    Multi-threaded apartment

    Unknown

    Currently mapped to MTA


    Once the ApartmentState property has been set, it cannot be changed again. No error or exception will result from attempting to set this property more than once.

    An alternative method is to use either the [STAThread] or [MTAThread] attribute before the first line of code in the project's dpr file. Although it is possible to use the following code to set the apartment model,

    Thread.CurrentThread.ApartmentState := ApartmentState.STA;

    using the appropriate attribute guarantees that the apartment state will be set up before any startup code is executed.

    The System.Threading.ThreadPool Class

    One of the nicest features of threading in the .NET framework is the addition of a thread pooling class. Saving thousands of lines of code, this class provides the means necessary for using threads as easy as calling a single method.

    Ideal for short-lived tasks, the ThreadPool class hides the underlying Thread class, taking away the flexibility and control that the Thread class provides.

    Many features of the .NET platform use threads from the thread pool. Examples using the thread pool include asynchronous file I/O, timers, socket connections, and the asynchronous execution of delegates.

    All AppDomains located within the same process share threads from the same thread pool. Figure 14.3 illustrates this relationship.

    Applications request a thread by using one of the QueueUserWorkItem() methods of the ThreadPool class. These methods take a WaitCallback delegate that specifies which method to execute on a thread pool thread. This method is added to an internal queue and is executed when a thread is available.

    Be careful when using any of the methods that begin with Unsafe because these methods bypass security checks in order to increase performance.

    An example of using threads from the ThreadPool is shown in Listing 14.4.

    Listing 14.4 Using ThreadPool Threads

    1:  program threadpool;
    2:  {$APPTYPE CONSOLE}
    3:  uses
    4:   System.Threading;
    5: 
    6:  type
    7:  TThreadPoolMe = class
    8:  public
    9:   // this method will be executed on a threadpool thread
    10:   procedure ThreadMePlease(state : System.Object);
    11:  end;
    12:
    13: procedure TThreadPoolMe.ThreadMePlease(state : System.Object);
    14: var
    15:  id : string;
    16: begin
    17:  id := 'n/a';
    18:  if assigned(state) then
    19:   id := state.ToString;
    20:
    21:  writeln(id,') Hello from the thread pool. Thread ID is ',
    22:   AppDomain.GetCurrentThreadID,' IsThreadPool = ',
    23:   Thread.CurrentThread.IsThreadPoolThread);
    24:
    25:  Thread.Sleep(2000);
    26: end;
    27:
    28: const
    29:  MAX_THREADS = 10;
    30: var
    31:  i : integer;
    32:  thrd : array[1..MAX_THREADS] of TThreadPoolMe;
    33: begin
    34:  writeln('The main thread''s id is ', AppDomain.GetCurrentThreadID);
    35:  // queue up a bunch of threads to use the thread pool
    36:  for i:=1 to MAX_THREADS do
    37:  begin
    38:   // create another instance of our class
    39:   thrd[i] := TThreadPoolMe.Create;
    40:   writeln('Queueing thread ', i);
    41:   // now queue up the ThreadMePlease method, passing i in for the state
    42:   System.Threading.ThreadPool.QueueUserWorkItem(
    43:         @thrd[i].ThreadMePlease, System.Object(i));
    44:  end;
    45:  // watch the re-use of the thread id's when this application runs
    46:  readln;
    47:  writeln('Done');
    48: end.

    Note: Find the code on the CD: \Code\Chapter 14\Ex03\.

    Listing 14.4 queues 10 threads to the thread pool for execution. Running this example will reveal how the CLR reuses existing threads by examining the reuse of thread IDs.


    Note - In addition to manually created threads and threads within the thread pool, the .NET Framework must also keep track of other threads. These threads include the main thread and the finalizer (or the garbage collector) thread. Unmanaged threads can also be running from PInvoke or COM interoperability as well.


    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





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