views:

888

answers:

4

What is the best and cleanest way to close a console application on windows mobile?

The application by default is invisible and you cannot see it in the running programs, which is great for running a background process, but sometimes the user might need to close it..

A: 

That's a great question. I once spent a long time trying to figure this out. Of course, we are assuming you can not (easily) return from Main. The correct answer on the desktop is System.Environment.Exit; But that method is conveniently not supported on CF.

An apparent second option is Application.Exit. That is on CF, but only applies to WinForms, and is in fact not guaranteed to exit your application.

So, throw an unhandled exception. ;)

EDIT: To kill it programatically from another app, you can look at Process.GetProcessById, and Process.Kill. Both of these are available on CF. You will have to somehow let the "killer" app figure out the "victim"'s ID. More convenient methods like Process.GetProcessesByName are not available on CF. This technique isn't that elegant, though, and there may be permissions issues.

You could also consider some kind of IPC (inter-process communication), perhaps one overviewed in this previous Windows Mobile answer.

Matthew Flaschen
that does not sound like a clean solution hehe. I was considering a 2nd application that terminates the first one. is something like that possible with console apps? since they seem to be invisible
Marcom
A: 

How would a user be able to close it if the application is not visible in the UI?

tomlog
Killing the process!?
Galilyou
someone proposed that the main process checks periodically a file to see if the flag to exit is set and terminates if it finds it. But Im searching for a better way of doing things.
Marcom
+1  A: 

Exit Main. Seriously. If you need someone to be able to exit is manually, there needs to be some mechanism like a shell icon and menu or a program in the Programs folder of something. How else would the user even know it's running? Any one of those visual cues would then set a named system event, and inside your Console app you'd have something listening for the same event (likely a worker). When it gets set, you take the actions required to shut down.

ctacke
A: 

I decided to to read a boolean (keep alive) in the config file and have another application set it to false when I want to exit.

Its not that responsive but at least I can exit cleanly..

Marcom