Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Forms - Multiple Event Loops

Tags:

.net

winforms

I have a Windows Forms (.NET) application that can have multiple documents open simultaneously.

It would be convenient to have each document (form) running its own event loop. With brief experimentation, starting several event loops in their own STA threads seems to work. Is there any reason why this is a bad idea?

like image 831
fuzzyman Avatar asked Oct 29 '08 21:10

fuzzyman


People also ask

How do you link two events to a single event handler in Windows Forms?

To connect multiple events to a single event handler in C#Click the name of the event that you want to handle. In the value section next to the event name, click the drop-down button to display a list of existing event handlers that match the method signature of the event you want to handle.

Will WinForms be deprecated?

WinForms won't be deprecated until Win32 is ... which could be quite sometime! WPF on the other hand has few direct dependencies on Win32 so could potentially form the basis of a "fresh start" UI layer on a future version of windows.


2 Answers

I think it's perfectly fine do create multiple message loops on different threads. The only thing to watch out for is when dealing with 3rd party UI toolkits, they sometimes store handles as static (instead of ThreadStatic) members and if you have multiple UI threads in your application, it will have problems (in my case, I found that the menu / toolbar keyboard accelerators did not work properly).

One of the big reasons for doing this is if you have modal dialogs that show up on the different modeless dialogs. If you put everything on the same message loop, then if one of the modeless dialogs has a modal dialog, the whole application (all the windows) are blocked until you dismiss the modal dialog.

And, like Kevin was saying, watch out for cross-window (cross-thread) calls. You can use Control.BeginInvoke or Control.Invoke to post delegate calls on the other UI threads.

The other thing to consider is how you will be exiting your process. You will most likely need to keep track of the message loops so you can stop them when you want to close everything out. If you don't care and just want the process to end when all the windows are closed, you can do that too.

like image 134
Garo Yeriazarian Avatar answered Sep 29 '22 16:09

Garo Yeriazarian


It might be smarter to use an MDI (Multiple Document Interface) container and child forms. In this case, each document would be in its own form, which technically means each document has its own message queue.

like image 44
OwenP Avatar answered Sep 29 '22 16:09

OwenP