Run a form in another thread

2019-08-28 15:06发布

问题:

i have five forms in my c# project. one host an httplistener that i want to run continionsly. when the listener gets a message, it passes it to a static class, which in turn calls the appropriate forms for another processing.

is it possible that the static class calls the new form in a new thread? if so please help me out

回答1:

The code in the forms should only deal with the visual aspects of the form. Anything else,especially http listeners, should be handled with separate classes running on background threads.



回答2:

"Calling a form" doesn't mean anything, I guess you'd only want to Show() it. Creating a form on a worker thread is never a good idea. Even if you do get the thread state right (STA and message loop), you'll have hard-to-solve Z-order and modality problems.

Simply use Control.Invoke to run code on the UI thread. It should create the form and call its Show() method.



回答3:

As Hans said, it may not be recommended, but if necessary, you can call System.Windows.Forms.Application.Run() from any thread. Just be careful and know what you are doing, if you do.