在运行外部流程时保持我的应用程序运行

时间:2017-01-20 22:44:21

标签: c# unity3d unity5

这是我的问题,我使用此代码在团结中运行外部流程:

    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时我尝试了一个空循环该应用程序再次冻结。

任何想法?

谢谢,

1 个答案:

答案 0 :(得分:2)

使用MyProcess.BeginOutputReadLine();时,您不应该致电MyProcess.StandardOutput.ReadToEnd();。此外,您也无法致电MyProcess.WaitForExit(),这将锁定该计划。

您应该订阅Exited事件。但是我相信该事件将在后台线程中引发,因此您需要使用其他一些机制来告诉UI它已完成读取,因为您无法直接与UI线程以外的线程中的组件进行通信。 / p>

我建议您使用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,然后等待协程完成并停止动画。