pcunite
pcunite

Reputation: 1197

Should every VCL form has its own message loop/pump for threading?

I'm attempting to implement a MVP pattern in my latest project. Currently using the VCL library that comes with C++ Builder 2007. My thinking is I don't need to do Application->Run(), or worse Application->CreateForm() which creates a main form and loop on that form. I don't want a main form, I want a main Presenter, instead.

My question then becomes how to create threaded TForms?

Option 1: If there is only one message loop (the Presenter) then every random thread in my system would have to post a message to this main thread and have it create forms.

Option 2: Every form has its own message loop. Now random threads can new and delete them as needed. Posting messages is still used for communications between them.

If option 2 is recommended does anyone have any advice on implementing this approach?

EDIT: How might I change the following to allow for creating the form using new and still allow the loop to work?

// Start VCL library
pApplication->Initialize();

// Create the Main form and assign the MainForm property
pApplication->CreateForm(__classid(TForm1), &pFormMain);

// Show the form
pFormMain->Show();

// Run the loop
pApplication->Run();

Upvotes: 2

Views: 895

Answers (2)

David Heffernan
David Heffernan

Reputation: 613412

You don't put each form in its own thread. You put each form in the main thread.

A thread only has one message loop. The exception to this is the special message loop that is run when a form is shown modally.

pApplication->Run(); runs your message loop. When posted messages are processed they get dispatched to the appropriate window procedure. When messages are sent they are delivered synchronously direct to the window procedure.

You can create and show as many forms as you like and service them all from the same message loop. Not only can you do this, it is the way to do things.

How you map this knowledge onto your MVP framework is another matter, but running your GUI out of a single thread is a fixed point in any solution.

EDIT

You ask how, with VCL, to run a message loop if you don't have a visible main form. You have two options:

  1. Create an invisible form before you callpApplication->Run();.
  2. Run your own message loop.

In my view option 1 is by far the better option.

Upvotes: 3

Ken White
Ken White

Reputation: 125749

You can't safely create threaded forms using the VCL, because the VCL isn't thread-safe.

Also, each form already contains it's own message loop. TApplication simply dispatches messages to each form's loop.

Upvotes: 1

Related Questions