Reputation: 535
Has anyone had to deal with trying to kill an app on a Windows Mobile 5 device?
It's a .net 3.5 winforms app that has a number of background threads that don't seem to be cleaned up properly when an exception is thrown. Which, I guess, is the case when a kill is issued as well. And so in both cases the process hangs on showing some 3 background threads, and it just won't go away without a reset.
Is there any way to eliminate such a process other than actually fix bugs in the code?
Upvotes: 1
Views: 2508
Reputation: 67188
You need to understand how threads, at least in CE (and likely the desktop) work. Normally when a process' primary (entry) thread quits, the OS scheduler is notified and all of it's worker threads are scheduled for termination. The next time those threads request quantum (a slice of processing time), they are killed - and this is the important bit.
If the background thread is "stuck" in a blocking OS call (e.g. WaitForSingleObject(INFINITE)
) then that thread will never request quantum from the scheduler. If the scheduler is never asked for time to run the thread, the thread is never given the opportunity to actually terminate.
This is the primary reason that worker threads should always have a timeout in their activity loops (I'd argue that if you ever use an infinite timeout anywhere, you're probably in error). Even if the timeout goes back and waits again, it gives the scheduler the opportunity to kill the thread.
You might try using the toolhelp APIs to terminate the process (which IIRC will suspend and resume the worker threads, giving the scheduler a chance to do it's work). I'm not certain it will work, but it's pretty easy to P/Invoke to try.
Upvotes: 2
Reputation: 33924
Does your application keep track of the background threads it's using? I know on a windows forms app, throwing an exception and killing the main application thread can leave background threads running, even if you kill the application at large. If the app is keeping track, you can explicitly kill the background threads as part of your exception handling, before the application crashes.
Otherwise, you can check periodically on the background threads to see if the main application is still running and if it's not, have them kill themselves. Not quite as clean, but another possibility.
Upvotes: 0