Example illustrating my project
static async Task Main()
{
await RunAsync("a.exe", string.Empty, string.Empty, 100000, null);
}
static async Task RunAsync(string fileName, string arguments, string workingDir, int timeLimit, string input)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fileName.ToString();
startInfo.Arguments = arguments.ToString();
startInfo.WorkingDirectory = workingDir;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.ErrorDialog = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
using (Process process = new Process())
{
process.StartInfo = startInfo;
StringBuilder output = new StringBuilder();
process.OutputDataReceived += (object sendingProcess, DataReceivedEventArgs e) =>
{
output.AppendLine(e.Data);
};
StringBuilder error = new StringBuilder();
process.ErrorDataReceived += (object sendingProcess, DataReceivedEventArgs e) =>
{
error.AppendLine(e.Data);
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (input != null)
await process.StandardInput.WriteLineAsync(input);
if (!process.WaitForExit(timeLimit))
process.Kill();
if (!string.IsNullOrWhiteSpace(error.ToString()))
{
return;
}
Console.WriteLine(output.ToString());
return;
}
}
I assume file a.exe
hangs. Process will Kill()
it when time limit.
If the main thread is improperly shut down, it will always run and show up in Task Manager.
Is there way for Process to self-destroy without main thread?