問題描述
我正在嘗試統一運行 exe 應用程序以執行某些功能,并且該 exe 文件在統一運行時將從我的麥克風獲取輸入,因此我必須等到它退出,而使用 waitforexit 允許 exe 接受輸入很好但這并不好,因為我在 exe 運行期間的統一應用程序會停止,直到我的 exe 完成,我想在我的 exe 運行時統一執行其他操作.
I'm trying to run an exe application in unity to perform some function and that exe file will take an input from my microphone when running in unity so i must wait until it exit while using waitforexit is nice to allow exe takes input but it's not good because my unity app during the exe running becomes stopped till it my exe finish and i want perform somethings else in unity while my exe running.
這是我的代碼:-
System.Diagnostics.Process p = new System.Diagnostics.Process();
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
因為它阻塞了主線程.您的問題有兩種解決方法:
You don't have to use WaitForExit
since it's blocking the main Thread. There are two workarounds for your issue:
1.將 EnableRaisingEvents
設置為 true
.訂閱 Exited
事件并使用它來確定打開的程序何時關閉.在 Update
函數中使用布爾標志來確定它是否仍處于打開狀態.
1.Set EnableRaisingEvents
to true
. Subscribe to the Exited
event and use that to determine when the opened program has closed. Use a boolean flag to determine if it is still opened or not in the Update
function.
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
但只在新的 Thread
中使用該代碼,這樣它就不會'不阻塞或凍結 Unity 的主線程.
2.Continue with your WaitForExit
but only use that code in a new Thread
so that it doesn't block or freeze Unity's main Thread.
//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
.請參閱 這個了解更多信息.
Note that you can't use Unity's API from this new Thread. If you want to do so, use UnityThread.executeInUpdate
. See this for more information.
這篇關于Waitforexit 統一中斷我正在運行的應用程序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!