What I basically want is to start AsyncCall and proceed with my code loading. I have Interface section that consumes lots of time (600+ms) and I want to load this code in independent thread.
I’ve tried to use AsyncCall to make something like this:
procedure Load;
begin
...
end;
initialization
AsyncCall(@Load, []); // or LocalAsyncCall(@Load)
However, this Load procedure actually starts in Main thread and not in the new created thread. How can I force the Load procedure to be loaded in any thread other than MainThread?
I can create TThread and Execute this but I want to force AsyncCall or LocalAsyncCall or anything from AsyncCall library to make to work.
Thanks for your help.
The problem is that your code is not retaining the
IAsyncCallinterface that is returned by theAsyncCallfunction.Because of this, the interface that is returned has its reference count decremented to zero as soon as the initialization section completes. This therefore frees the object that implements the interface which does this:
The key line is the call to
Syncwhich forces the asynchronous call to be executed to completion. All this happens in the main thread which explains the behaviour that you report.The solution is that you simply need to keep the
IAsyncCallinterface alive by storing it in a variable.In the real code you need to ensure that
Loadhad completed before running any code that is reliant onLoad. When your program reached a point where it requiredLoadto have been called it has to callSyncon theIAsyncCallinterface.So you might write it something like this.
The call
EnsureLoadedfrom other units that requiredLoadto have run. Or, alternatively, callEnsureLoadedfrom any methods exported byMyUnitthat depended onLoadhaving run. The latter option has much better encapsulation.