is it "OK" to call Application.Processmessages inside a Thread (not Main-Thread) or should I expect troubles?
is it "OK" to call Application.Processmessages inside a Thread (not Main-Thread) or should I expect troubles?
TApplication.ProcessMessages() is designed primarily to process VCL messages. You should not be receiving any VCL messages in a worker thread, unless you are creating and displaying TForm windows from worker threads. Which you should not be doing, since the VCL is not thread-safe and should not be used outside of the main UI thread.
But, that being said, if no VCL messages are received in a worker thread, calling ProcessMessages() in a worker thread is not itself harmful. It will dispatch any received messages (VCL or otherwise) to the appropriate window procedure in the calling thread. But, if you think you need manual message dispatching in a worker thread, you really need to question why you need that in the first place. Unless you are using COM apartment-threaded objects in worker threads, or posting custom thread messages to worker threads, there is very little use for running a message loop in a worker thread, and even then ProcessMessages() is not ideal for that purpose.
Calling Application.ProcessMessages from a thread other that main thread is really a bad idea because it is really aimed at VCL and VCL is not thread safe.
This being said, I have a lot of threads having a message loop so that it handle cooperative multitasking and inter-thread communication.
I always write my own message loop by calling Windows API:
while GetMessage(MsgRec, 0, 0, 0) do begin
TranslateMessage(MsgRec);
DispatchMessage(MsgRec)
end;
I make an heavy use of this in my ICS (Internet Component Suite) when an asynchronous TWSocket has to run in a thread. The code above is part of ICS in TIcsWndControl. TWSocket can easily handle hundreds of connection per thread but if you want to handle thousands of connections, you have to use threads.
Using Windows messages between worker threads or main thread and worker thread is often a solution to avoid calling TThread.Synchronize: When you PostMessage from a thread, the sending thread continue to run and the receiving thread (the one which created the window handle passed in PostMessage) will gracefully handle the message in his own context.