[英]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.我正在编写一个小型控制台应用程序(将作为服务运行),它基本上会在运行时启动 Java 应用程序,如果 Java 应用程序关闭,则自行关闭,如果关闭则关闭 Java 应用程序。
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.我想我的前两个工作正常,但我不知道如何检测 .NET 应用程序何时关闭,以便我可以在发生之前关闭 Java 应用程序。 Google search just returns a bunch of stuff about detecting Windows shutting down.谷歌搜索只返回一堆关于检测 Windows 关闭的内容。
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");
}
}
}
}
Ahh MineCraft :)啊我的世界 :)
Since your Console App will eventually become a windows service, look into OnStop , OnPowerEvent , onPause and onShutDown methods of the ServiceBase class.由于您的控制台应用程序最终将成为 Windows 服务,因此请查看ServiceBase类的OnStop 、 OnPowerEvent 、 onPause和onShutDown方法。
You will need to register this event in your Main method:您需要在 Main 方法中注册此事件:
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)
{
}
}
您需要向Application.ApplicationExit事件添加一个事件处理程序。
You said it will run as a service.您说它将作为服务运行。
In that case protected method OnStop() of ServiceBase class will be called.在这种情况下,ServiceBase 类的受保护方法 OnStop() 将被调用。
http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onstop(v=VS.85).aspx http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onstop(v=VS.85).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.