Forum > General
How to create form in thread?
lazpas:
Thanks.
eljo:
you don't.
Zoran:
Apart from the main thread, no other thread is allowed to interact with GUI.
I don't remember why it is so, but I know that this limitation exists not only in LCL, but also in Delphi's VCL, as well as in other GUI libraries used with other popular programming languages.
Having said that, you can freely access LCL from another thread (let's call it Thread2) in synchronized methods of Thead2, which actually means that Thread2 stops executing and passes the method to the main thread, to be executed in the context of the main thread; only after the main thread is finished with this method, Thread2 continues its own life.
An example here: https://www.thoughtco.com/synchronizing-threads-and-gui-delphi-application-1058159
This example updates progress bars, but it is the same with creating new forms or any interaction with LCL controls.
Warfley:
--- Quote from: Zoran on May 05, 2023, 11:46:52 am ---I don't remember why it is so, but I know that this limitation exists not only in LCL, but also in Delphi's VCL, as well as in other GUI libraries used with other popular programming languages.
--- End quote ---
Short answer, threading is hard and GUI system APIs are already complex enough with all their events and interactions. If you start having them in parallel this would be impossible to debug and test. Both the restriction of the LCL and Delphis VCL comes from the underlying system. Basically the windows API does not support threaded access to GUIs, it's the same for QT and while Cocoa does AFAIK not enforce this, it is also recommended to not access the GUI from other threads there. So it's not an LCL or Lazarus limitation, but a limitation of the underlying systems and APIs.
This is for example why javascript has introduced async-await style co routines, to allow parallelism on a single thread, because as a mostly GUI and interactive system focused language threading is very limited in javascript, but instead non preemptive co-routines are used to avoid the problems of having to synchronize threads.
It should also be noted that most datatypes in Pascal are not thread safe either, Arrays, Strings and most classes are not threadsafe.
cai:
actually,on windows, API: MessageBox can be called in a sub-thread, maybe it is specail API, or coincidence,it dose not mean MS stand with that!
Navigation
[0] Message Index
[#] Next page