我正在尝试统一运行一个 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/