Process.Exited Evento

Definición

Se produce cuando termina un proceso.

public:
 event EventHandler ^ Exited;
public event EventHandler Exited;
member this.Exited : EventHandler 
Public Custom Event Exited As EventHandler 

Tipo de evento

Ejemplos

En el ejemplo de código siguiente se crea un proceso que imprime un archivo. Genera el Exited evento cuando se cierra el proceso porque la EnableRaisingEvents propiedad se estableció cuando se creó el proceso. El Exited controlador de eventos muestra la información del proceso.

using System;
using System.Diagnostics;
using System.Threading.Tasks;

class PrintProcessClass
{
    private Process myProcess;
    private TaskCompletionSource<bool> eventHandled;

    // Print a file with any known extension.
    public async Task PrintDoc(string fileName)
    {
        eventHandled = new TaskCompletionSource<bool>();

        using (myProcess = new Process())
        {
            try
            {
                // Start a process to print a file and raise an event when done.
                myProcess.StartInfo.FileName = fileName;
                myProcess.StartInfo.Verb = "Print";
                myProcess.StartInfo.CreateNoWindow = true;
                myProcess.EnableRaisingEvents = true;
                myProcess.Exited += new EventHandler(myProcess_Exited);
                myProcess.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred trying to print \"{fileName}\":\n{ex.Message}");
                return;
            }

            // Wait for Exited event, but not more than 30 seconds.
            await Task.WhenAny(eventHandled.Task,Task.Delay(30000));
        }
    }

    // Handle Exited event and display process information.
    private void myProcess_Exited(object sender, System.EventArgs e)
    {
        Console.WriteLine(
            $"Exit time    : {myProcess.ExitTime}\n" +
            $"Exit code    : {myProcess.ExitCode}\n" +
            $"Elapsed time : {Math.Round((myProcess.ExitTime - myProcess.StartTime).TotalMilliseconds)}");
        eventHandled.TrySetResult(true);
    }

    public static async Task Main(string[] args)
    {
        // Verify that an argument has been entered.
        if (args.Length <= 0)
        {
            Console.WriteLine("Enter a file name.");
            return;
        }

        // Create the process and print the document.
        PrintProcessClass myPrintProcess = new PrintProcessClass();
        await myPrintProcess.PrintDoc(args[0]);
    }
}
Imports System.Diagnostics

Class PrintProcessClass

    Private WithEvents myProcess As Process
    Private eventHandled As TaskCompletionSource(Of Boolean)

    ' Print a file with any known extension.
    Async Function PrintDoc(ByVal fileName As String) As Task

        eventHandled = New TaskCompletionSource(Of Boolean)()
        myProcess = New Process
        Using myProcess
            Try
                ' Start a process to print a file and raise an event when done.
                myProcess.StartInfo.FileName = fileName
                myProcess.StartInfo.Verb = "Print"
                myProcess.StartInfo.CreateNoWindow = True
                myProcess.EnableRaisingEvents = True
                AddHandler myProcess.Exited, New EventHandler(AddressOf myProcess_Exited)
                myProcess.Start()

            Catch ex As Exception
                Console.WriteLine("An error occurred trying to print ""{0}"":" &
                vbCrLf & ex.Message, fileName)
                Return
            End Try

            ' Wait for Exited event, but not more than 30 seconds.
            Await Task.WhenAny(eventHandled.Task, Task.Delay(30000))
        End Using
    End Function

    ' Handle Exited event and display process information.
    Private Sub myProcess_Exited(ByVal sender As Object,
            ByVal e As System.EventArgs)

        Console.WriteLine("Exit time:    {0}" & vbCrLf &
            "Exit code:    {1}" & vbCrLf & "Elapsed time: {2}",
            myProcess.ExitTime, myProcess.ExitCode,
            Math.Round((myProcess.ExitTime - myProcess.StartTime).TotalMilliseconds))
        eventHandled.TrySetResult(True)
    End Sub

    Shared Sub Main(ByVal args As String())

        ' Verify that an argument has been entered.
        If args.Length <= 0 Then
            Console.WriteLine("Enter a file name.")
            Return
        End If

        ' Create the process and print the document.
        Dim myPrintProcess As New PrintProcessClass
        myPrintProcess.PrintDoc(args(0)).Wait()

    End Sub
End Class

Comentarios

El Exited evento indica que se ha salido del proceso asociado. Esta repetición significa que el proceso finalizó (anulado) o se cerró correctamente. Este evento solo puede producirse si el valor de la EnableRaisingEvents propiedad es true.

Hay dos maneras de recibir una notificación cuando se cierra el proceso asociado: de forma sincrónica y asincrónica. La notificación sincrónica significa llamar al método para bloquear el WaitForExit subproceso actual hasta que se cierre el proceso. La notificación asincrónica usa el Exited evento , que permite que el subproceso de llamada continúe la ejecución mientras tanto. En este último caso, EnableRaisingEvents debe establecerse true en para que la aplicación que llama reciba el evento Exited.

Cuando el sistema operativo cierra un proceso, notifica a todos los demás procesos que tienen controladores registrados para el evento Exited. En este momento, el identificador del proceso que acaba de salir se puede usar para acceder a algunas propiedades como ExitTime y HasExited que el sistema operativo mantiene hasta que libera ese control por completo.

Nota:

Incluso si tiene un identificador para un proceso cerrado, no puede volver a llamar Start a para volver a conectarse al mismo proceso. La llamada a Start libera automáticamente el proceso asociado y se conecta a un proceso con el mismo archivo, pero un elemento completamente nuevo Handle.

Para obtener más información sobre el uso del Exited evento en Windows Forms aplicaciones, vea la SynchronizingObject propiedad .

Se aplica a