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);
}
}
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)
{
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) { }
"", python script.
script , , .
.
cancelToken.Cancel();
.