I am still having problems with figuring out how to create winforms in a separate UI thread that I discussed here.
In trying to figure this out I wrote the following simple test program. I simply want it to open a form on a separate thread named ‘UI thread’ and keep the thread running as long as the form is open while allowing the user to interact with the form (spinning is cheating). I understand why the below fails and the thread closes immediately but am not sure of what I should do to fix it.
using System; using System.Windows.Forms; using System.Threading; namespace UIThreadMarshalling { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var tt = new ThreadTest(); ThreadStart ts = new ThreadStart(tt.StartUiThread); Thread t = new Thread(ts); t.Name = 'UI Thread'; t.Start(); Thread.Sleep(new TimeSpan(0, 0, 10)); } } public class ThreadTest { Form _form; public ThreadTest() { } public void StartUiThread() { _form = new Form1(); _form.Show(); } } }
On a new thread, call Application.Run passing the form object, this will make the thread run its own message loop while the window is open.
Then you can call .Join on that thread to make your main thread wait until the UI thread has terminated, or use a similar trick to wait for that thread to complete.
Example: