Why Does my Thread Terminate Immediately After Showing a Windows Form?

c#, multithreading, winforms

Solution

The problem is not in the posted snippet. You'll need to start a new message loop with Application.Run() or Form.ShowDialog(). You'll also need to take care of thread properties so it is suitable to act as a UI thread. For example:

  Thread t = new Thread(() => {
    Application.Run(new Form2());
    // OR:
    //new Form2().ShowDialog();
  });
  t.SetApartmentState(ApartmentState.STA);
  t.IsBackground = true;
  t.Start();

There are some awkward choices here. The form cannot be owned by any form on your main thread, that usually causes Z-order problems. You'll also need to do something meaningful when the UI thread's main form is closed. Sloppily solved here by using IsBackground.

Windows was designed to support multiple windows running on one thread. Only use code like this if you really have to. You should never have to...

Problem

I have a Windows Form Application (Form1) that allow the user to open another Forms (FormGraph). In order to open the FormGraph App I use a thread that open it. Here is the code that the thread is running: ``` private void ThreadCreateCurvedGraph() { FormGraph myGraph = new FormGraph(); myGraph.CreateCurvedGraph(...); myGraph.Show(); } ``` My problem is that `myGraph` closed right after it's open. 1) Does anyone know why this is happening and how to make `myGraph` stay open? 2) After the user closed `myGraph`, How do I terminate the thread? Many thanks!

Original source

Related problems