My TThread.Execute method updates a label's caption after a calculation. It usually works. Sometimes the window stops responding or the debugger stops in widgetset code.
I added ShowMessage in the worker to see how far it got. Now I have a second problem with a dialog.
Re: Worker finishes the job and occasionally breaks the label
LCL controls belong on the main thread. That includes reading control properties and showing dialogs. A run that happened to succeed does not make worker access safe.
Here is a complete worker unit. Execute prepares its result, then Synchronize runs ApplyText on the main thread:
Create this worker on the main thread with an existing label, retain the worker reference, then call Start. Keep the label and its form alive until the worker finishes. Since FreeOnTerminate is false, the owner must free the worker after completion.
For Unix targets using POSIX threads, put cthreads first in the main program's uses clause, before Interfaces and Forms. The worker unit does not replace that setup.
Read the error message. Then read it again.
Re: Worker finishes the job and occasionally breaks the label
Yes. The worker waits while the main thread executes the method. The LCL application loop normally services these requests.
A console application without that loop must arrange for the main thread to call CheckSynchronize. Calling it from the worker is not a substitute.
Keep synchronized methods short. Sending thousands of tiny updates can leave the main thread busy updating a progress display instead of handling the interface.
Re: Worker finishes the job and occasionally breaks the label
Use a breakpoint and inspect the call stack for this problem. A modal ShowMessage changes timing and enters message processing, even when called on the main thread. It can hide a timing fault or introduce another one.
Also test closing the form during work. Prevent its destruction until the worker can no longer access the label. Synchronization controls which thread runs a method, not whether its target still exists.
Re: Worker finishes the job and occasionally breaks the label