Tutorial :Getting multiple UI threads in Windows Forms


I'm trying to figure out a way to make user controls run in their own UI threads. Is this possible? I'm trying to prevent a module-based application from crashing due to a single module.

Any thoughts?


That's not possible. However, with some non-trivial code, you can have different windows running in separate threads. Each window will have its own message loop.


Another way you could think of is to write your controls in a special way. You can handle all events in your controls by creating a new thread that will run all the logic.


Unfortunately all UI controls run on the same UI thread. Therefore any code running on this thread that could potentially lead to a hang situation would need to be coded with some sort of timeout logic.

DateTime startTime = DateTime.Now;  while(DateTime.Now.Subtract(startTime).TotalSeconds < 30)  {       //do something  }  

Otherwise, as Orlangur stated earlier, all event handler code would need to be run in separate threads. You would still however need to monitor these threads to determine if they've been running too long and shut them down. As such you might as well implement the type of logic above as it would be a lot less work and more maintainable.


I suppose it's not a matter of the program crashing. Exceptions can be caught of course, but the issue is in hanging controls. For the sake of this situation, here's an example:

public void Button1_Click(object sender, EventArgs args)  {       while(true) {}  }  

If this code were to run in a control, an exception wouldn't throw, but it would hang. I'm trying to determine a way to catch this and remove the control module from the application.


Running controls in different threads should be possible. A little hacking and windows overrides and it should be doable.

I am thinking you can create a GUI control in another thread, then move it to a common window (main gui thread) with the win api SetParent. SetParent can be used to "hijack" other windows, so you should be able to grab the controls this way. But of course there might be focus issues and other issues, but might be doable.

I used that once to put my own button onto MS Messenger.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »