JustLogin
JustLogin

Reputation: 1890

C#: close process on app's process' killing (with taskman)

I'm very new to C# so my question may sound rediculous. I'm developing an application which sometimes need to run ffmpeg. As you guess, this ffmpeg process must be killed when it's host app was closed. I use such code for this task:

AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
private void OnProcessExit(object sender, EventArgs e)
   {
      proc.Kill();
   }

This works fine, when the app is closed correctly (via it's interface or with Taskman - Applications). The problem is that OnProcessExit event won't trigger, if the program's process was killed (with Taskman - Processes). As far as I know, killing process and closing program actions are not the same on the low level, but I guess, killing process is a command to it and it can be handled with C# tools. So, is it possible, to close child process in this case?

Upvotes: 7

Views: 1387

Answers (3)

Kushal Patil
Kushal Patil

Reputation: 205

I think Try this

Application.Exit();

Upvotes: 1

Johan Polson
Johan Polson

Reputation: 117

let your host program submit its program ID as parameter, and then listen if the program exits.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    static class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length != 0)
                new System.Threading.Thread( new System.Threading.ParameterizedThreadStart(handelexit)).Start(args[0]);

            // your code here
        }

        static void handelexit(object data)
        {
            int id = System.Convert.ToInt32(data.ToString());

            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(id);
            while (!p.HasExited)
                System.Threading.Thread.Sleep(100);

            System.Environment.Exit(0);
        }
    }
}

Upvotes: 0

Leotsarev
Leotsarev

Reputation: 1062

I recommend to use job objects (as per Scott Miller suggestion). Another option can be have special helper app for your app, which does following:

  • Start your app
  • When your app crashed, clean up after it.

But job objects is definitely better option, it specifically made for this

Upvotes: 0

Related Questions