I created a generic class to execute a console application while redirecting its output to a RichTextBox
in my form.
The code works just fine, but the Process.Exited
event never fires even though the console application exists normally after it completes it function.
Also, WaitForExit
doesn't seem to do anything and any code I write after it is never executed for some reason.
Here's the class (updated):
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);
}
}
Here's the code I use in the 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: I'm aware that there are several posts about this issue, and I've checked them, but none of them helped, so here I am.