NET (C #): Events about process exit __net

Source: Internet
Author: User

For the current program, the Process.exited event does not work, the following code:

static void Main ()
{
    var pro = Process.getcurrentprocess ();
    Pro. EnableRaisingEvents = true;
    Pro. Exited + + new EventHandler (pro_exited);
}

static void Pro_exited (object sender, EventArgs e)
{
    throw new notimplementedexception ();
}

The result will not be thrown by any exceptions.

The solution is to use Appdomain.processexit, which is invoked when the default application domain is unloaded due to a process exit:

static void Main ()
{
    AppDomain.CurrentDomain.ProcessExit + = new EventHandler (currentdomain_processexit);
}

static void Currentdomain_processexit (object sender, EventArgs e)
{
    throw new notimplementedexception ();
}

Run the code, the exception will be thrown smoothly.

However, if the process is forced to quit, none of the above events will be run.

If a program is used to monitor the process.exited event of another program, the process.exited will still run even if another process is forced to end.

Code:

 static void Main () {//Open notepad var pro = new Process (); Pro.
    Startinfo.filename = "Notepad"; Pro.
    EnableRaisingEvents = true; Pro.
    exited + = new EventHandler (pro_exited); Pro.
    Start (); Pro.
WaitForExit (); static void Pro_exited (object sender, EventArgs e) {Console.WriteLine ("Another process has been terminated"); 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.