title: Multiple UI Threads - Winforms
body: <p>I want to create multiple UI threads in my application. I have simulated the scenario as below. I am creating a new window / form on a button click in a <em>background</em> thread</p>
  
  <pre><code>namespace WindowsFormsApplication1
  {
      public partial class Form1 : Form
      {
          public Form1()
          {
              InitializeComponent();
          }
  
          private void button1_Click(object sender, EventArgs e)
          {
              var thread = new Thread(() =&gt;
              {
                  Form f = new Form();
                  Application.Run(f);
              });
  
              // thread.IsBackground = true; -- Not required. See Solution below
              thread.SetApartmentState(ApartmentState.STA);
              thread.Start();
          }
      }  
  }
  </code></pre>
  
  <p>Note that - I am doing IsBackground = true bacause when the user closes on the main form, the child forms/windows should also close down. <strong>Is there a more cleaner/graceful way to achieve the same ?</strong></p>
  
  <blockquote>
    <p>EDIT - I want to create dedicated UI threads for each window. I will
    have 10 such windows displaying real-time data in parallel.</p>
  </blockquote>
  
  <p><strong>Solution</strong> - Is this fine ? (as per <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.exit%28v=VS.100%29.aspx" rel="noreferrer">msdn</a> and <em>Hans'</em> comments below)
  have set the Apartment state (see code above)</p>
  
  <pre><code>protected override void OnClosed(EventArgs e)
  {
      Application.Exit();
  }
  </code></pre>