c# - Waitforexit 统一中断我正在运行的应用程序

标签 c# unity3d process background

我正在尝试统一运行一个 exe 应用程序以执行某些功能,并且该 exe 文件将在统一运行时从我的麦克风获取输入,所以我必须等到它退出,而使用 waitforexit 可以很好地允许 exe 获取输入但这并不好,因为我的 unity 应用程序在 exe 运行期间停止,直到我的 exe 完成,我想在我的 exe 运行时统一执行其他事情。

这是我的代码:-

System.Diagnostics.Process p = new System.Diagnostics.Process();

    p.StartInfo = new System.Diagnostics.ProcessStartInfo("E:\\app\\dist\\app.exe");
    p.StartInfo.WorkingDirectory = @"\Assets\\app\\dist\\app.exe";
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    p.Start();
    p.WaitForExit();

最佳答案

您不必使用 WaitForExit,因为它会阻塞主线程。您的问题有两种解决方法:

1。将 EnableRaisingEvents 设置为 true。订阅Exited事件并使用它来确定打开的程序何时关闭。在 Update 函数中使用 bool 标志确定它是否仍处于打开状态。

bool processing = false;

void Start()
{
    processing = true;

    Process p = new Process(); ;
    p.StartInfo = new System.Diagnostics.ProcessStartInfo("E:\\app\\dist\\app.exe");
    p.StartInfo.WorkingDirectory = @"\Assets\\app\\dist\\app.exe";
    p.StartInfo.CreateNoWindow = true;
    p.EnableRaisingEvents = true;
    p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    p.Exited += new EventHandler(OnProcessExit);
    p.Start();
}

private void OnProcessExit(object sender, EventArgs e)
{
    processing = false;
}


void Update()
{
    if (processing)
    {
        //Still processing. Keep reading....
    }
}

2。继续您的WaitForExit仅在新的线程中使用该代码,这样它就不会'阻止或卡住 Unity 的主线程。

//Create Thread
Thread thread = new Thread(delegate ()
{
    //Execute in a new Thread
    Process p = new Process(); ;
    p.StartInfo = new System.Diagnostics.ProcessStartInfo("E:\\app\\dist\\app.exe");
    p.StartInfo.WorkingDirectory = @"\Assets\\app\\dist\\app.exe";
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    p.Start();
    p.WaitForExit();

    //....
});
//Start the Thread and execute the code inside it
thread.Start();

请注意,您不能从这个新线程使用 Unity 的 API。如果您想这样做,请使用 UnityThread.executeInUpdate。参见 this获取更多信息。

关于c# - Waitforexit 统一中断我正在运行的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50080274/

相关文章:

c# - unity “Can not play a disabled audio source”

c# - 使用带偏移量的基址指针读取进程内存

c# - TextAlign 不适用于 Controls.Find

c# - data-ajax-update 在 dotnet core jquery unobtrusive ajax 中不起作用

c# - SMTP 服务器需要安全连接或客户端未通过身份验证。

c# - 静态变量与静态属性

c# - 从 Input.GetAxis() 读取时,transform.Translate 似乎加速和减速对象

android - 如何检查用户是否已授予相机或位置权限(android)UNITY

C#:将作业分包给多处理器机器上的工作进程

java - Java 中的 FFMPEG 问题