Using the Asynchronous Programming Library

From RAD Studio
Jump to: navigation, search

Go Up to Using the RTL in Multi-Device Applications


The RTL provides the Asynchronous Programming Library (APL). The APL takes the advantage of using the PPL in order to provide support for asynchronous opperations within TComponent. Multithread opperation already allows you to manually customize the management of your applications asynchronously, however the APL facilitates considerably this task as it embeds support for asynchronous programming in a component.

APL overview

The APL provides the base class TBaseAsyncResult in order to support asynchronous calls. Therefore it simplifies the management of the asynchronous parts of your application in the following manner:

  • You can manage the behavior of an asynchronous call to a target method. In particular, you can select where to schedule an asynchronous call for its execution:
Note: If you do nothing, the call executes synchronously on the main thread by default.

While the target method executes in a background thread, the original caller thread is able to continue working parallely on other synchonous tasks as usual. Once the target method finishes processing its tasks it returs the results back to the caller thread.

Note: If you schedule the call to a target method in a descendant of the caller thread, this target method does not operate asynchonously as the caller thread processes it entirely.

How to Use the APL

In order to start using asynchronous operations you have to:

  • Include a TComponent in order to support asynchronous programming.
  • Use the IAsyncResult interface to access the functionalities that TBaseAsyncResult provides for implementing asynchronous programming.
  • Call the BeginInvoke method to start an asynchronous call to a target method. You can manage the thread where the target method call executes. The current thread continues working normally until the IAsyncResult completes the execution of the target method and returns to the caller the results of the asynchronous method.
  • Call the EndInvoke method to wait until the IAsyncResult completes. You need to call EndInvoke for each call to BeginInvoke.
  • You can include a callback method in the call to BeginInvoke. Thus the callback method is called when the target method ends. If you proceed in this way, you can call EndInvoke within the callback so as to obtain the results. Otherwise you can call EndInvoke in the caller thread as mentioned above.

See Also