【发布时间】:2011-01-18 17:15:32
【问题描述】:
我不想再次发布这个问题,但我回答了我自己的上一篇帖子,认为我已经修复了它(我没有)。基本上,当我的 c# .NET 应用程序关闭时,我想删除它创建的正在运行的 Java 进程。最初的问题是我试图将 processID 保存到静态类成员变量(这显然不起作用)。我在网上找到了一个 Global Class 示例并使用了它,但是它仍然没有关闭该过程。
调试它不能正常工作。我猜它只是创建了应用程序的一个新实例,而不是运行我构建的那个,甚至将工作目录设置为“Bin”目录也不起作用。所以我现在只需要从 Bin 目录运行我的 .exe。
namespace MinecraftDaemon
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting Minecraft Daemon...");
Arguments CommandLine = new Arguments(args);
// Hook ProcessExit Event
AppDomain.CurrentDomain.ProcessExit += new EventHandler(Current_ProcessExit);
if (CommandLine["file"] != null && CommandLine["memory"] != null)
{
// Launch the Application (Command Line Parameters)
LaunchMinecraft(CommandLine["file"], CommandLine["memory"]);
}
else
{
// Launch the Application (Default Parameters)
LaunchMinecraft("minecraft_server.jar", "1024");
}
}
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))
{
GlobalClass.ProcessID = minecraftProcess.Id;
Console.WriteLine("Process ID is " + GlobalClass.ProcessID);
minecraftProcess.WaitForExit();
}
}
catch
{
// Log Error
}
}
static void Current_ProcessExit(object sender, EventArgs e)
{
// Loop the Current Windows Processes
foreach (Process winProcess in Process.GetProcesses())
{
Console.WriteLine("WinProcessID is " + winProcess.Id + " GlobalClass.ProcessID is " + GlobalClass.ProcessID);
// If this is our Process, shut it down
if (winProcess.Id == GlobalClass.ProcessID)
{
Process.GetProcessById(GlobalClass.ProcessID).Kill();
}
}
}
}
}
【问题讨论】:
-
你的代码能到达
Current_ProcessExit中的WriteLine吗? -
一些 Java 应用程序不会正常退出(如果有运行的非守护线程拒绝停止),所以这可能是它不起作用的原因之一。
-
@biziclop:您能否提供该声明的参考资料?我很好奇。:)
-
@casblanca:我不确定,它关闭得太快了,我看不到。至于 Java 应用程序没有正常退出,我想这可能是问题所在。这个问题有什么可能的解决方案吗?
-
更正,我只是从 cmd.exe 运行了我的 .exe,然后用 ctrl+c 将其关闭,它没有命中 Console.WriteLine()。