When you use objects from the class hierarchy, their properties and methods are not guaranteed to be thread-safe. That is, accessing properties or executing methods may perform some actions that use memory which is not protected from the actions of other threads. Because of this, a main thread is set aside to access VCL objects. This is the thread that handles all Windows messages received by components in your application.
If all objects access their properties and execute their methods within this single thread, you need not worry about your objects interfering with each other. To use the main thread, create a separate routine that performs the required actions. Call this separate routine from within your thread's Synchronize method. For example:
procedure TMyThread.PushTheButton; begin Button1.Click; end; ... procedure TMyThread.Execute; begin ... Synchronize(PushTheButton); ... end;
void __fastcall TMyThread::PushTheButton(void) { Button1->Click(); } void __fastcall TMyThread::Execute() { ... Synchronize((TThreadMethod)PushTheButton); ... }
Synchronize waits for the main thread to enter the message loop and then executes the passed method.
Object |
Description |
Data access component |
Data access components are thread-safe as follows: For BDE-enabled datasets, each thread must have its own database session component. The one exception to this is when you are using Microsoft Access drivers, which are built using a Microsoft library that is not thread-safe. For dbExpress, as long as the vendor client library is thread-safe, the dbExpress components will be thread-safe. ADO and InterBaseExpress components are thread-safe. When using data access components, you must still wrap all calls that involve data-aware controls in the Synchronize method. Thus, for example, you need to synchronize calls that link a data control to a dataset by setting the DataSet property of the data source object, but you don't need to synchronize to access the data in a field of the dataset. For more information about using database sessions with threads in BDE-enabled applications, see Managing multiple sessions. |
Control |
Controls are not thread-safe. |
Graphic |
Graphics objects are thread-safe. You do not need to use the main VCL thread to access TFont, TPen, TBrush, TBitmap, TMetafile (VCL only), or TTIcon. Canvas objects can be used outside the Synchronize method by locking them. |
List |
While list objects are not thread-safe, you can use a thread-safe version, TThreadList, instead of TList. |
Call the CheckSynchronize routine periodically within the main thread of your application so that background threads can synchronize their execution with the main thread. The best place to call CheckSynchronize is when the application is idle (for example, from an OnIdle event handler). This ensures that it is safe to make method calls in the background thread.
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
|
What do you think about this topic? Send feedback!
|