问题描述
我正在尝试统一运行 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.