9

I want to send a message to a thread and handle it in the thread. How can I do this in Delphi? I guess PostMessage is the way to go, but the examples I've seen so far are describing the other way, i.e. from the thread to main thread.

Sebastian Zartner
  • 18,808
  • 10
  • 90
  • 132
delphist
  • 285
  • 5
  • 8

3 Answers3

6

I won't even try and explain or write any code. Just look at this tutorial. It's a little old, but very good imho. Multithreading - The Delphi Way

Steve
  • 6,382
  • 3
  • 41
  • 66
6

You can either have a message loop (possibly with a hidden notification window) in your thread and send a Windows message to it, or you can use a more native (less-GUI) way of doing it, such as a queue protected by a critical section combined with a manual-reset event that the thread waits on and the sending thread signals.

A more general solution is a producer-consumer queue, which in the classic implementation uses a couple of semaphores to keep track of consumers and producers and a third semaphore for mutually exclusive access to the queue; however, more optimal producer-consumer queues are available on the net.

Barry Kelly
  • 41,404
  • 5
  • 117
  • 189
  • 4
    And remember, kids: DO NOT use .Synchronize() if performance is your goal :) – F.D.Castel Nov 09 '08 at 07:39
  • Could not agree more. If that was an answer instead of a comment I would have voted it up. For a nice little rant about the dos and donts of TThread see also http://newsgroups.cryer.info/borland/public.delphi.internet.winsock/200507/0507273541.html – mghie Nov 10 '08 at 10:06
3

Why would you need to do it? It is only for one reason that I ever had to create a message loop in a secondary thread, and that is because the thread used COM objects. The calls to OleInitialize() and OleUnitialize() are a sign that you need a standard GetMessage() loop. In that case it's also necessary to just post messages to that thread, using PostThreadMessage(), because normal blocking synchronization calls would interfere with the message loop. Otherwise, just don't do it.

If you are at Delphi 2007 or 2009, be sure to look into OmniThreadLibrary by Primož Gabrijelčič, it should make your job much easier.

mghie
  • 32,028
  • 6
  • 87
  • 129
  • Why would you need to do it? For example, i have a thread thats polling events from a server in every 1000msec but i need to change the polling rate to 5000msec. Stopping then starting the thread again for this purpose is too much. – john_who_is_doe Jan 20 '16 at 10:30
  • @tdiop: To achieve this no message needs to be sent to the thread, there are many other, better ways to do it. Check the other answers for inspiration. – mghie Jan 20 '16 at 11:28