Michael Pfiffer
Michael Pfiffer

Reputation: 115

Detect Application Shutdown in C# NET?

I am writing a small console application (will be ran as a service) that basically starts a Java app when it is running, shuts itself down if the Java app closes, and shuts down the Java app if it closes.

I think I have the first two working properly, but I don't know how to detect when the .NET application is shutting down so that I can shutdown the Java app prior to that happening. Google search just returns a bunch of stuff about detecting Windows shutting down.

Can anyone tell me how I can handle that part and if the rest looks fine?

namespace MinecraftDaemon
{
    class Program
    {
        public static void LaunchMinecraft(String file, String memoryValue)
        {
            String memParams = "-Xmx" + memoryValue + "M" + " -Xms" + memoryValue + "M ";
            String args = memParams + "-jar " + file + " nogui";
            ProcessStartInfo processInfo = new ProcessStartInfo("java.exe", args);
            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;

            try
            {
                using (Process minecraftProcess = Process.Start(processInfo))
                {
                    minecraftProcess.WaitForExit();
                }
            }
            catch
            {
                // Log Error
            }
        }

        static void Main(string[] args)
        {
            Arguments CommandLine = new Arguments(args);

            if (CommandLine["file"] != null && CommandLine["memory"] != null)
            {
                // Launch the Application
                LaunchMinecraft(CommandLine["file"], CommandLine["memory"]);
            }
            else
            {
                LaunchMinecraft("minecraft_server.jar", "1024");
            }
        }
    }
}

Upvotes: 4

Views: 5527

Answers (4)

sidon
sidon

Reputation: 1482

You said it will run as a service.

In that case protected method OnStop() of ServiceBase class will be called.

http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onstop(v=VS.85).aspx

Upvotes: 0

tenor
tenor

Reputation: 1105

Ahh MineCraft :)

Since your Console App will eventually become a windows service, look into OnStop, OnPowerEvent, onPause and onShutDown methods of the ServiceBase class.

Upvotes: 4

VoodooChild
VoodooChild

Reputation: 9784

You will need to register this event in your Main method:

Application.ApplicationExit += new EventHandler(AppEvents.OnApplicationExit);

and add the event handler

public void OnApplicationExit(object sender, EventArgs e)
{
    try
    {
        Console.WriteLine("The application is shutting down.");
    }
    catch(NotSupportedException)
    {
    }
}

Upvotes: 5

Anon.
Anon.

Reputation: 59983

You'll want to add an event handler to the Application.ApplicationExit event.

Upvotes: 0

Related Questions