Search code examples
c#application-shutdown

How can I make sure a C# console program ALWAYS exits?


I've written a small C# console app that is used by many users on a shared storage server. It's runtime should always be < 3 seconds or so, and is run automatically in the background to assist another GUI app the user is really trying to use. Because of this, I want to make sure the program ALWAYS exits completely, no matter if it throws an error or what not.

In the Application_Startup, I have the basic structure of:

try
{
    // Calls real code here
}
catch
{
    // Log any errors (and the logging itself has a try with empty catch around it
    // so that there's no way it can causes problems)
}
finally
{
    Application.Shutdown();
}

I figured that with this structure, it was impossible for my app to become a zombie process. However, when trying to push new versions of this app, I repeatedly find that I cannot delete and replace the executable because the "file is in use", meaning that it's hanging on someone's computer out there, even though it should only run for a few seconds and always shutdown.

So, how is it that my app is seemingly becoming a hanging process on peoples' computers with the code structure I have? What am I missing?

Edit: Added "Application." to resolve ShutDown() for clarity.


Solution

  • There are two options here:

    1. Your console application doesn't really finish in 3 seconds, but rather takes a lot longer. You need to debug it and see what takes it that long.
    2. Your console application takes 3 seconds to exit, but it is run every minute by the GUI, and you have more than 40 users, so the probability of finding the executable unused are slim.

    If it's the first one, and you don't want to debug it, you can always start a second thread, wait for 3 seconds and then kill the entire process.