Process.Exited 永远不会触发
我创建了一个通用类来执行控制台应用程序,同时将其输出重定向到表单中的 RichTextBox
。
该代码工作得很好,但是即使控制台应用程序在完成其功能后正常存在,Process.Exited
事件也永远不会触发。
此外,WaitForExit
似乎没有执行任何操作,并且由于某种原因我在它之后编写的任何代码都不会执行。
这是该类(更新) ):
using System;
using System.Diagnostics;
public class ConsoleProcess
{
private string fpath;
public ConsoleProcess(string filePath)
{
fpath = filePath;
}
public void Run(string arguments)
{
var procInfo = new ProcessStartInfo()
{
FileName = fpath,
Arguments = arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
};
var proc = new Process() { EnableRaisingEvents = true, StartInfo = procInfo };
proc.OutputDataReceived += Proc_DataReceived;
proc.ErrorDataReceived += Proc_DataReceived;
proc.Exited += Proc_Exited;
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
}
public event EventHandler<EventArgs>? ProcessExited;
private void Proc_Exited(object? sender, EventArgs e)
{
ProcessExited?.Invoke(sender, e);
}
public event EventHandler<DataReceivedEventArgs>? DataReceived;
private void Proc_DataReceived(object sender, DataReceivedEventArgs e)
{
DataReceived?.Invoke(sender, e);
}
}
这是我在 Form
中使用的代码:
ConsoleProcess process = new("console_app.exe");
process.DataReceived += Process_DataReceived;
process.ProcessExited += Process_Exited;
private async void Execute()
{
await Task.Run(() =>
{
process.Run("--arguments");
});
}
private void Process_DataReceived(object? sender, System.Diagnostics.DataReceivedEventArgs e)
{
//do stuff
}
private void Process_Exited(object? sender, EventArgs e)
{
MessageBox.Show("Done");
}
PS:我知道有几个关于这个问题的帖子,我已经检查过它们,但没有一个有帮助,所以我在这里。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要解决您所面临的问题,请尝试添加
Proc.WaitForexit();
。代码:
如果要使用
task
,请尝试以下内容:Note :我将class
consoleprocess
重命名为<代码> HelperProcess 作为原始名称似乎有些欺骗性。创建一个新项目 - Windows表单应用程序
ProcessTest
.NET 5
创建一个类(名称) :helperprocess.cs)
helperProcess :
添加按钮添加到Form1 (名称:BTNRUN)
单击
event> event handler打开属性窗口
添加
formclosed
事件处理程序to form1form1 strong>:
资源:
To solve the issue that you're facing, try adding
proc.WaitForExit();
.Code:
If you want to use
Task
, then try the following:Note: I renamed class
ConsoleProcess
toHelperProcess
as the original name seems somewhat deceptive.Create a new project - Windows Forms App
ProcessTest
.NET 5
Create a class (name: HelperProcess.cs)
HelperProcess:
Add button to Form1 (name: btnRun)
Click
event handlerOpen Properties Window
Add
FormClosed
event handler to Form1Form1:
Resources: