保留我的应用程序 运行 而 运行 一个外部进程

Keep my app running while running an external process

这是我的问题,我正在 运行使用以下代码在 unity 中设置一个外部进程:

    MyProcess = new Process();
    MyProcess.EnableRaisingEvents = true;
    MyProcess.StartInfo.UseShellExecute = false;
    MyProcess.StartInfo.RedirectStandardOutput = true;
    //MyProcess.StartInfo.RedirectStandardInput = true;
    //MyProcess.StartInfo.RedirectStandardError = true;
    MyProcess.StartInfo.FileName = DataPath + "myfile.bat";
    MyProcess.OutputDataReceived += new DataReceivedEventHandler(DataReceived);
    MyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    MyProcess.StartInfo.CreateNoWindow = true;
    MyProcess.Start();
    MyProcess.BeginOutputReadLine();
    string Output = MyProcess.StandardOutput.ReadToEnd();
    UnityEngine.Debug.Log(Output);

    MyProcess.WaitForExit();

除了 bat 文件中的进程需要将近 1-2 分钟,我的应用程序完全冻结外,一切都很好。我只想在处理动画时 运行 动画(不继续代码)..

我尝试了线程处理,但它 运行 是后台线程,并且没有找到任何成功的方法来阻止应用程序在完成之前继续处理代码,当我尝试空循环时Thread.IsAwake 为 false 应用再次冻结。

有什么想法吗?

谢谢,

当您使用 MyProcess.BeginOutputReadLine(); 时,您不应调用 MyProcess.StandardOutput.ReadToEnd();。另外你也不能调用 MyProcess.WaitForExit(),那会锁定程序。

您应该改为订阅 Exited 事件。但是我相信该事件将在后台线程上引发,因此您需要使用其他一些机制来告诉 UI 它已完成读取,因为您不能直接与 [= 以外的线程中的组件对话27=]线程。

我建议您使用 WaitUntil 观察一个变量,并在 Exited 触发时设置该变量。

private IEnumerator StartAndWaitForProcess()
{
    bool programFinished = false;
    var waitItem = new WaitUntil(() => programFinished);
    MyProcess = new Process();
    MyProcess.EnableRaisingEvents = true;
    MyProcess.StartInfo.UseShellExecute = false;
    MyProcess.StartInfo.RedirectStandardOutput = true;
    //MyProcess.StartInfo.RedirectStandardInput = true;
    //MyProcess.StartInfo.RedirectStandardError = true;
    MyProcess.StartInfo.FileName = DataPath + "myfile.bat";
    MyProcess.OutputDataReceived += new DataReceivedEventHandler(DataReceived);
    MyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    MyProcess.StartInfo.CreateNoWindow = true;

    //Sets the bool to true when the event fires.
    MyProcess.Exited += (obj, args) => programFinished = true;

    MyProcess.Start();
    MyProcess.BeginOutputReadLine();
    //string Output = MyProcess.StandardOutput.ReadToEnd(); //This locks up the UI till the program closes. 
    //UnityEngine.Debug.Log(Output); This log should be in the DataReceived function.

    //MyProcess.WaitForExit(); This also locks up the UI

    //This waits for programFinished to become true.
    yield return waitItem;
}

函数 StartAndWaitForProcess() 需要用 StartCoroutine 调用,您可以等待协程完成并停止动画。