开发者

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["fi开发者_如何学编程le"] != null && CommandLine["memory"] != null)
            {
                // Launch the Application
                LaunchMinecraft(CommandLine["file"], CommandLine["memory"]);
            }
            else
            {
                LaunchMinecraft("minecraft_server.jar", "1024");
            }
        }
    }
}


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜