Second message loop a Windows Forms application?

D

DoB

Hi,

The main message loop is started with Application.Run(new MainForm());
What if I wanted to create another message loop in a thread for a different
form, say ThreadForm?
How to do this?

Regards,
DoB
 
N

Nicholas Paldino [.NET/C# MVP]

DoB,

Well, you would start a new thread and then call the static Run method
on the Application class, passing in your new form.

Note that there is no guarantee that this will work on multiple threads
(at least from what I can tell in the documentation for the Run method) nor
is there and explicit statement that it won't work, so I would be cautious
of doing this.

Why do you want to do this though? Why do you need a second message
loop?
 
T

Tom Shelton

DoB,

Well, you would start a new thread and then call the static Run method
on the Application class, passing in your new form.

Note that there is no guarantee that this will work on multiple threads
(at least from what I can tell in the documentation for the Run method) nor
is there and explicit statement that it won't work, so I would be cautious
of doing this.

I've done it - and it works. My reason was to recieve events from a COM
component created on that thread. It wouldn't raise any events, until I
created a message pump on the thread. Calling Application.Run fixed the issue.
 
S

Stephen Martin

Actually, this is guaranteed to succeed. The documentation explicitly states
that it will create a message pump on the calling thread and that it will
fail, specifically, if there is already a message pump for that particular
thread. In addition, the method is documented as thread safe - a condition
that couldn't be met if two threads calling the method simultaneously could
lead to undefined behaviour.

While this isn't a common scenario it is by no means all that rare, I've
seen it used a number of times for various reasons over the years. Mostly
for thread specific handling of COM objects but other reasons as well.

Nicholas Paldino said:
DoB,

Well, you would start a new thread and then call the static Run method
on the Application class, passing in your new form.

Note that there is no guarantee that this will work on multiple threads
(at least from what I can tell in the documentation for the Run method)
nor is there and explicit statement that it won't work, so I would be
cautious of doing this.

Why do you want to do this though? Why do you need a second message
loop?


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

DoB said:
Hi,

The main message loop is started with Application.Run(new MainForm());
What if I wanted to create another message loop in a thread for a
different form, say ThreadForm?
How to do this?

Regards,
DoB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top