0

How do I implement cancellation when running a cmd-file correctly? Currently I use this code:

public async IAsyncEnumerable<string?> ExecuteCmdFile(string parameters, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
    var startInfo =
        new ProcessStartInfo(_cmdFilePath, parameters) { RedirectStandardOutput = true, CreateNoWindow = true };
    using var p = new Process { StartInfo = startInfo };
    p.Start();
    while (!p.HasExited)
    {
        if (cancellationToken.IsCancellationRequested)
        {
            p.Kill();
            yield return "Operation aborted";
        }
        else
        {
            yield return await p.StandardOutput.ReadLineAsync().ConfigureAwait(false);
        }
    }
}

Cancellation generally works but - depending on the task currently running - it may take a while, because the process first has to wait for ReadLineAsync() to return a value before cancellationToken.IsCancellationRequested() is checked again and can be acted upon.

Any ideas on how to solve this?

Jan
  • 3,825
  • 3
  • 31
  • 51

0 Answers0