异步进程启动并等待它完成 [英] Async process start and wait for it to finish
问题描述
我是新来在.NET中的线程模型。你会用什么:
I am new to the thread model in .net. What would you use to:
- 在开始处理一个文件(process.StartInfo.FileName =文件名;)过程
- 等待用户一段时间后,关闭程序或放弃线程
- 如果用户关闭了进程,删除文件
启动过程,并等待应做不同的线程比主线程,因为此操作不会影响应用程序。
Starting the process and waiting should be done on a different thread than the main thread, because this operation should not affect the application.
例如:
我的应用程序生成的HTML报告。用户可以用鼠标点击的地方,并说查看报告 - 现在我检索报告的内容在一个临时文件并启动处理HTML文件即默认浏览器的进程。问题是,我不能清理,即删除临时文件。
My application produces an html report. The user can right click somewhere and say "View Report" - now I retrieve the report contents in a temporary file and launch the process that handles html files i.e. the default browser. The problem is that I cannot cleanup, i.e. delete the temp file.
推荐答案
,并等待一定是异步 - 我不是在开玩笑,但不是在这方面有矛盾?但是,因为你开始一个进程
的已退出
事件可能会有所帮助:
"and waiting must be async" - I'm not trying to be funny, but isn't that a contradiction in terms? However, since you are starting a Process
, the Exited
event may help:
ProcessStartInfo startInfo = null;
Process process = Process.Start(startInfo);
process.EnableRaisingEvents = true;
process.Exited += delegate {/* clean up*/};
如果你想真正等待(超时等),则:
If you want to actually wait (timeout etc), then:
if(process.WaitForExit(timeout)) {
// user exited
} else {
// timeout (perhaps process.Kill();)
}
有关异步等待,或许只是使用一个不同的线程?
For waiting async, perhaps just use a different thread?
ThreadPool.QueueUserWorkItem(delegate {
Process process = Process.Start(startInfo);
if(process.WaitForExit(timeout)) {
// user exited
} else {
// timeout
}
});
这篇关于异步进程启动并等待它完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!