Search code examples
c#processbackgroundworker

Killing external process inside background worker


I'm having this code inside a DoWork of a background worker:

Process downloadConvert = new Process();
downloadConvert.StartInfo.FileName = @"process.exe";
downloadConvert.StartInfo.Arguments = "args here";
downloadConvert.StartInfo.UseShellExecute = false;
downloadConvert.StartInfo.RedirectStandardOutput = true;
downloadConvert.StartInfo.RedirectStandardError = true;
downloadConvert.StartInfo.CreateNoWindow = true;
downloadConvert.EnableRaisingEvents = true;
downloadConvert.OutputDataReceived += (s, er) =>
{
    Debug.WriteLine(er.Data);
    if (er.Data != null && er.Data != "")
    {
        metadata trackInfo = JsonConvert.DeserializeObject<metadata>(er.Data);
        title.Add(trackInfo.title);
    }

    if (fetchInfoBW.CancellationPending == true)
    {
        e.Cancel = true;
        downloadConvert.Kill();
        downloadConvert.WaitForExit();
        return;
    }
};

downloadConvert.Start();
downloadConvert.BeginOutputReadLine();
downloadConvert.WaitForExit();

I've added cancellation support to my worker and I want it to exit after I press a button. Since the worker is actually the process itself and the process keeps sending output while active, I'm trying to find a way to terminate/kill/stop it from the OutputDataReceived. The code above seems to successfully kill the process(it no longer sends debug output) but for some reason the worker's completed event is never fired and the application stops there.


Solution

  • The solution was to declare the Process globally and then initialize it locally. That way it was visible in the whole application and I was able to kill it on button press while I was also calling the CancelAsync() method on the worker.