0

I have an application, where a create a new window for my graphic. I create it next way:

var thread = new Thread(() =>
{
    var win = new MyWindow();
    win.Show();
    Dispatcher.Run();
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

The problem is, that when I close Main application, additional window is still on and I need to close it manually. I set ShutDownMode in my App.xaml to OnMainWindowClose and overrided OnClosed:

protected override void OnClosed(EventArgs e)
{
    base.OnClosed(e);
    Application.Current.Shutdown();
}

But it does not help me.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sasha
  • 833
  • 1
  • 20
  • 40
  • Try `Environment.Exit(0);` or `Process.GetCurrentProcess().Kill();` – Ahmed KRAIEM Jun 26 '13 at 14:55
  • Do you need the ApartmentState ? Isn't it responsible for this behavior ? – C4stor Jun 26 '13 at 14:55
  • @AhmedKRAIEM that is a way to make sure the application stops, but that is the brutal way and not the most clean way. – Max Jun 26 '13 at 14:56
  • @AhmedKRAIEM although it is a valid answer:) – Max Jun 26 '13 at 14:58
  • But...why are you doing it this way? You are effectively spawning a new application by doing this. Is that *really* what you want to achieve? – Rikalous Jun 26 '13 at 15:17
  • @Rikalous what do you mean by "You are effectively spawning a new application by doing this"? Isn't it just a new window? Why do I spawn new application? – Sasha Jun 27 '13 at 07:00
  • @Sasha because you are creating the window on a new thread, it is now independent from the calling application. See answer... – Rikalous Jun 27 '13 at 10:11

4 Answers4

4

Add

thread.IsBackground = true;

before run the thread.

Refer to http://msdn.microsoft.com/en-us/library/ms741870.aspx

Bill Zhang
  • 1,909
  • 13
  • 10
2

Make sure that your thread(s) is/are stopped, before the application exits. You could do this by using Thread.Abort or wait for it using Thread.Join.

But those are nasty ways to end or wait for a thread. The best way is to use a bool to stop it from running.

Here is how to stop your thread the "Clean" way: https://stackoverflow.com/a/10664959/1661209

Community
  • 1
  • 1
Max
  • 12,622
  • 16
  • 73
  • 101
2

If you want to establish a relationship between windows you should set the Owner property of the new window thus:

var childWindow = new ChildWindow();
childWindow.Owner = this;
childWindow.Show();

Now, if you close the main window, all its children will close too.

Rikalous
  • 4,514
  • 1
  • 40
  • 52
1

Keep a reference to the thread that you spawn and when exiting the application, you signal the thread to exit somewhow (perhaps via a ManualResetEvent). After that you have to wait for the thread to exit by joining it.

_thread.Join();
Patrik Svensson
  • 13,536
  • 8
  • 56
  • 77