ULSAlgorithms 1.1.0-g3e5595996d
High-performance exact and heuristic algorithms for uncapacitated lot sizing
Loading...
Searching...
No Matches
ExternalSolverProcessProbe.cs
Go to the documentation of this file.
1using System.Diagnostics;
2
4
5/// <summary>
6/// Executes short solver command-line probes and captures their output.
7/// </summary>
8public sealed class ExternalSolverProcessProbe
9{
10 /// <summary>
11 /// Runs one external process and captures stdout, stderr and exit code.
12 /// </summary>
13 public async ValueTask<ExternalSolverProcessProbeResult> RunAsync(
14 string executablePath,
15 IEnumerable<string> arguments,
16 CancellationToken cancellationToken = default)
17 {
18 ArgumentException.ThrowIfNullOrWhiteSpace(executablePath);
19 ArgumentNullException.ThrowIfNull(arguments);
20
21 var startInfo =
22 new ProcessStartInfo
23 {
24 FileName = executablePath,
25 WorkingDirectory =
26 Path.GetDirectoryName(executablePath) ??
27 Environment.CurrentDirectory,
28 UseShellExecute = false,
29 RedirectStandardOutput = true,
30 RedirectStandardError = true,
31 CreateNoWindow = true
32 };
33
34 foreach (string argument in arguments)
35 {
36 startInfo.ArgumentList.Add(argument);
37 }
38
39 using var process =
40 new Process
41 {
42 StartInfo = startInfo,
43 EnableRaisingEvents = true
44 };
45
46 try
47 {
48 if (!process.Start())
49 {
50 throw new InvalidOperationException(
51 $"Unable to start '{executablePath}'.");
52 }
53
54 Task<string> stdoutTask =
55 process.StandardOutput.ReadToEndAsync(
56 cancellationToken);
57
58 Task<string> stderrTask =
59 process.StandardError.ReadToEndAsync(
60 cancellationToken);
61
62 try
63 {
64 await process.WaitForExitAsync(
65 cancellationToken);
66 }
67 catch (OperationCanceledException)
68 {
69 TryKill(process);
70 throw;
71 }
72
73 string stdout =
74 await stdoutTask;
75
76 string stderr =
77 await stderrTask;
78
80 process.ExitCode,
81 stdout,
82 stderr);
83 }
84 catch (OperationCanceledException)
85 {
86 throw;
87 }
88 catch
89 {
90 TryKill(process);
91 throw;
92 }
93 }
94
95 private static void TryKill(
96 Process process)
97 {
98 try
99 {
100 if (!process.HasExited)
101 {
102 process.Kill(
103 entireProcessTree: true);
104 }
105 }
106 catch
107 {
108 // Best-effort cleanup only.
109 }
110 }
111}
Executes short solver command-line probes and captures their output.
async ValueTask< ExternalSolverProcessProbeResult > RunAsync(string executablePath, IEnumerable< string > arguments, CancellationToken cancellationToken=default)
Runs one external process and captures stdout, stderr and exit code.