1

I have a WPF application which used to shutdown via Environment.Exit. Since this caused problems with my automated UI tests, I changed the exiting application to Application.Current.ShutDown.

This works fine, except there is a thread which is waiting to be pulsed (Monitor.Wait), which keeps the process running since it never gets pulsed anymore.

I thought that would be a no brainer to fix, but from the point where my application exits (the Application.Current.ShutDown) it's rather hard to retrieve a reference to the object which holds the waiting thread (in order to force pulse it, so that it can exit).

I tried to google an appropriate answer, but not much luck yet. Is there an "easy way" out of this? Or should I start refactoring already? :)

Some snippets:

Thread is created like this

workerThread = new Thread(Worker) { Name = logName, IsBackground = true};

In the Worker method, Monitor.Wait is called

while ((action = GetNextTask(out task)) == ProductPreparationAction.None)
{
    Monitor.Wait(preparationTasks);
}
bas
  • 13,550
  • 20
  • 69
  • 146
  • 1
    You are looking at the wrong thread for the problem, one that has IsBackground set to *true* can't stop an app from terminating. Use the Debug + Windows + Threads debugger window to find the troublemaker. – Hans Passant Aug 04 '14 at 20:51

1 Answers1

1

Nevermind my comment. Start refactoring :).

First of all, there should be a way for the while loop to end when before the app stops. Perhaps you can use and propagate a CancellationToken all the way down to the Worker method.

If you want to keep your loose coupling, you should be able to pulse by creating an event in the class that calls Application.Current.ShutDown and by subscribing to it in the class where the Worker method is (and call Pulse in the event handler).

If you do this, then you can store the CancellationToken in this class and flag it when the event is received.

That event should be raised before calling Application.Current.ShutDown.

Marcel N.
  • 13,726
  • 5
  • 47
  • 72