问题描述
我要:
- 显示带有文本框的表单.
- 运行一个外部程序(为便于示例,请注意notepad.exe).
- 继续允许用户在记事本运行时将数据输入到表单文本框中.
- 在记事本关闭时运行更多(继续)本机表单代码.除其他外,这将更新表格.
我在使这种情况发生时遇到问题.我知道有很多类似问题的帖子,但是还没有找到适合我的解决方案.
I'm having problems making this happen. I'm aware of a multitude of posts about this similar issue, but haven't found a solution that works for me.
我尝试过:
- 进行waitforexit,但这当然会阻止UI,并且用户无法输入数据.
- 尝试进行异步过程调用,该过程完成时将调用另一个方法.这会导致从另一个线程调用新方法而无法更新表单的问题.
- 在用户界面中执行等待/睡眠循环,但这又会自然地阻塞用户界面.
对于简单的Windows窗体程序,最简洁,最简单的解决方案是什么?没有使用额外的类,并且所有代码都在 Form1类中.
What would be the neatest, and simplest solution for a simple Windows Form program? There are no extra classes used, and all code is in the Form1 class.
推荐答案
进程退出时, Process
类将触发 Exited
事件.您可以向该事件添加处理程序,以在进程退出时执行代码而不会阻塞UI线程:
The Process
class fires an Exited
event when the process exits. You can add a handler to that event to execute code when the process exits without blocking the UI thread:
process.EnableRaisingEvents = true;
process.Exited += (s, args) => DoStuff();
或者,您可以创建一个 Task
来表示该过程的完成,以利用TPL实现异步:
Alternatively you could create a Task
that represents the completion of the process to leverage the TPL for asynchrony:
public static Task WhenExited(this Process process)
{
var tcs = new TaskCompletionSource<bool>();
process.EnableRaisingEvents = true;
process.Exited += (s, args) => tcs.TrySetResult(true);
return tcs.Task;
}
这将允许您编写:
await process.WhenExited();
UpdateUI();
这篇关于Windows窗体在不阻止UI的情况下运行外部进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!