Question

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");
            }
        }
    }
}
Was it helpful?

Solution

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)
    {
    }
}

OTHER TIPS

Ahh MineCraft :)

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top