问题
I routinely pass the main form handle to other threads so that they can post messages back to the main thread. I saw that on Sept 28, 2013, Remy Lebeau stated:
...the TWinControl.Handle property is not thread-safe, either. You should use the TApplication.Handle property instead, or use AllocateHWnd() to create your own window.
in this answer to a question about passing strings.
How is the handle property not safe? Does it change during the life of the program?
回答1:
How is the
Handle
property not safe?
When you access the Handle
property, if the window handle has not been created, then it is created on demand. If you access the Handle
property from a thread other than the GUI thread, then this means you create the window on the wrong thread.
Does it change during the life of the program?
Yes, the window handle can change if the window is re-created.
I routinely pass the main form handle to other threads so that they can post messages back to the main thread.
In this case, you are probably not accessing the Handle
property away from the main thread. It sounds like (although I cannot see your code) you are accessing Handle
on the main thread and passing that value to the other thread.
However, window recreation is the problem for you. Since your window is subject to recreation, you simply cannot rely on that handle outliving your thread. Whether or not your window will ever be recreated is hard to predict. The VCL does not perform recreation lightly. However, in my view it is far better to be safe than sorry. So, use AllocateHWnd
and take control of the lifetime of this window.
来源:https://stackoverflow.com/questions/31460970/is-the-tform-handle-thread-safe