Cheapest way to protect access of variables from inside a thread and from the VC

Giganews Newsgroups
Subject: Cheapest way to protect access of variables from inside a thread and from the VC
Posted by:  Ross McMillan (
Date: Fri, 7 Oct 2005

I have a threaded email object based on a TThread that creates a TidSMTP and
TidMessage.  The object is declared as:

  TThreadedEmail = class (TThread)

    ThreadedEmailState        : TThreadedEmailState ;
    ThreadedEmailResult      : TThreadedEmailResult ;
    ThreadedEmailJobName      : ShortString ;
    ThreadedEmailResultString : ShortString ;
    TimeEmailStartedmS        : longword ;
    DateTimeEmailStarted      : TDateTime ;

    procedure AddAttachment (AttachmentFileID : TFilename) ;
    procedure SendThreadedEmail ;
    procedure AbortThreadedEmail ;
    function  TimeSendingmS : longword ;

    constructor Create (parJobName    : ShortString ;
                        parSMTPServer  : ShortString ;
                        parUserID      : ShortString ;
                        parPassword    : ShortString ;
                        parFromAddress : ShortString ;
                        parToAddress  : ShortString ;
                        parSubject    : ShortString ;
                        parBody        : ANSIString ) ;

    destructor Destroy; override ;

    { Private declarations }

    SMTPClient          : TidSMTP ;
    EmailMessage        : TidMessage ;

    procedure Execute; override;

The threads are all created and destroyed from the main loop and it all
seems to work fine.  My question - the thread itself updates the state and
result variables and strings while it runs, but I want to be able to display
the thread status from the main loop.  I realise this brings into play the
issue of two threads (one being the VCL thread) accessing a variable at the
same time and I'm wondering what is the most convenient way of managing
this - should I create a critical section with each thread and bracket the
accesses to the variables from within the thread with the CS enter and
leave?  If I do this, do I need to take any steps when accessing the
variables from the VCL thread?  Or are the thread-safe data types likely to
be a more conveniet way to go?