c# - 从 C# 控制台应用程序杀死 Java 进程

标签 c# java .net

我刚才发布了这个问题,但我解决了另一个问题并遇到了另一个问题。我即将把这个程序部署到 28 台主机上,所以我想在我这样做之前确保它能正常工作。

我写了一个小的 c# NET 应用程序,它基本上是 Java 应用程序的包装器,当我的应用程序启动时,Java 应用程序也会启动,当我的应用程序关闭时,它也会关闭,等等。

一切正常,除了当我关闭我的应用程序时,Java 应用程序继续运行。当我创建流程时,我将 Process var 存储在方法之外的变量中,然后在我的应用程序关闭时使用它。无论出于何种原因,它都不会终止 Java 应用程序。

class Program
{
    private static Process minecraftProcess;

    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))
            using (minecraftProcess = Process.Start(processInfo))
            {
                minecraftProcess.WaitForExit();
            }
        }
        catch
        {
            // Log Error
        }
    }

    static void Main(string[] args)
    {
        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");
        }
    }

    static void Current_ProcessExit(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(10000);

        // If we have an active Minecraft Service, Shut it down
        if (minecraftProcess != null)
        {
            minecraftProcess.Kill();
        }
    }
}

最佳答案

您不能在 ProcessExit 处理程序中Sleep

documentation状态:

The total execution time of all ProcessExit event handlers is limited, just as the total execution time of all finalizers is limited at process shutdown. The default is two seconds. An unmanaged host can change this execution time by calling the ICLRPolicyManager::SetTimeout method with the OPR_ProcessExit enumeration value.

关于c# - 从 C# 控制台应用程序杀死 Java 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4719356/

相关文章:

java - 在基于 Swing 的应用程序中使用 JSlider 实现查找媒体文件

.net - FSharp.Core中 `id`函数的作用是什么?

c# - 当被要求修复程序中的错误时,您会发现 100 多个实例

c# - 如何在测试平板电脑(即非开发机器)上安装Windows8应用程序;关于签名损坏的错误

java - 读取 MimeMessage - MimeMultipart 无法转换为 MimeMultipart

c# - 如何从 C# 中的 DataGridView 单元格中提取分号分隔值

Java:使用计时器移动 jLabel 两次

c# - 表达式表示 `variable' ,其中预期为 `method group'

c# - 使用自定义域调试 Azure 网站

c# - 在 Linux (Ubuntu) 上从 C# (Mono) 使用 GnuPG