8

It seems which Synchronize cannot be used from a Thread created using CreateAnonymousThread, so the question is : How i can update a VCL component from inside of a Thread created using CreateAnonymousThread?

TThread.CreateAnonymousThread(procedure
 begin
  //do something
  UpdateCompnent();//how I can update a VCL component from here?   
 end
).Start;
Salvador
  • 16,132
  • 33
  • 143
  • 245

3 Answers3

10

You can use synchronize in this case, e.g.:

TThread.Synchronize(nil, procedure begin UpdateComponent(); end);

And if you want asynchronous method call execution within the main thread, you can use TThread.Queue, e.g.:

TThread.Queue(nil, procedure begin UpdateComponent(); end);
Linas
  • 5,485
  • 1
  • 25
  • 35
  • @David: That OP uses/asks about synchronize may just be because he wants to avoid threading issues, not necessarily because he needs synchronous execution. – Marjan Venema Jul 19 '11 at 06:29
4

You could also use PostMessage to safely queue, or SendMessage to safely synchronize from an anonymous thread.

Warren P
  • 65,725
  • 40
  • 181
  • 316
  • +, because I always favor `PostMessage` for component synchronization over the `Synchronize` method: no chance of dead-locks, no waiting in the working thread. But it does require a bit more work. – Cosmin Prund Jul 19 '11 at 05:32
  • PostMessage isn't comparable with Synchronize. – David Heffernan Jul 19 '11 at 06:13
  • If you need to get a bit of data (state) from a background thread and out into the foreground thread, safely, quickly, and without side effects or bugs, it's entirely comparable. – Warren P Oct 05 '12 at 21:58
1

You can use PostMessage(Form.Handle, WM_UPDATEMYCOMP, 0, 0);

You can define your own message id, wparam, lparam, with a bit of work you can turn them into more complicated parameters.

Darkerstar
  • 924
  • 1
  • 8
  • 17
  • 1
    You mean SendMessage rather than PostMessage in this situation. – David Heffernan Jul 19 '11 at 06:13
  • 1
    Note that accessing the `TWinControl.Handle` property from a worker thread context is not thread-safe. If the `Handle` is being recreated during that time, such as by a call to `TWinControl.RecreateWnd()`, then the thread can end up taking owership of the new `HWND` (and the main thread leaks an `HWND`), causing the `TForm` to stop working correctly. If you need to pass messages to a main thread `HWND` from a worker thread, use the `TApplication.Handle` window or the `AllocateHWND()` function instead. – Remy Lebeau Jul 19 '11 at 18:30