How to stop async process through CancellationToken?

I found under the code to execute some process without freezing the user interface. This code is executed when you click the "Get started" button. And I think that users will stop this work with the Stop button. So I found this article on MSDN .. https://msdn.microsoft.com/en-us/library/jj155759.aspx . But it was difficult to apply this CancellationTokento this code. Can anyone help with this issue?

I use only the method public static async Task<int> RunProcessAsync(string fileName, string args).

Code (from https://stackoverflow.com/a/3/310/ ):

public static async Task<int> RunProcessAsync(string fileName, string args)
{
    using (var process = new Process
    {
        StartInfo =
        {
            FileName = fileName, Arguments = args,
            UseShellExecute = false, CreateNoWindow = true,
            RedirectStandardOutput = true, RedirectStandardError = true
        },
        EnableRaisingEvents = true
    })
    {
        return await RunProcessAsync(process).ConfigureAwait(false);
    }
}

// This method is used only for internal function call.
private static Task<int> RunProcessAsync(Process process)
{
    var tcs = new TaskCompletionSource<int>();

    process.Exited += (s, ea) => tcs.SetResult(process.ExitCode);
    process.OutputDataReceived += (s, ea) => Console.WriteLine(ea.Data);
    process.ErrorDataReceived += (s, ea) => Console.WriteLine("ERR: " + ea.Data);

    bool started = process.Start();
    if (!started)
    {
        //you may allow for the process to be re-used (started = false) 
        //but I'm not sure about the guarantees of the Exited event in such a case
        throw new InvalidOperationException("Could not start process: " + process);
    }

    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    return tcs.Task;
}

Using:

var cancelToken = new CancellationTokenSource();
int returnCode = async RunProcessAsync("python.exe", "foo.py", cancelToken.Token);
if (cancelToken.IsCancellationRequested) { /* something */ }

"", python script. script , , . .

cancelToken.Cancel();

.

+4
1

, process.Kill() :

cancellationToken.Register(() => process.Kill());

:

  1. , , InvalidOperationException.
  2. Dispose() CancellationTokenRegistration Register(), CancellationTokenSource , , , CancellationTokenSource.

( ) № 2 № 1, catch.

+9

Source: https://habr.com/ru/post/1619346/


All Articles