Process.Exited Process.Exited Process.Exited Process.Exited Event

Definizione

Si verifica al termine di un processo.Occurs when a process exits.

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

Esempi

Esempio di codice seguente crea un processo che consente di stampare un file.The following code example creates a process that prints a file. Genera il Exited eventi quando il processo viene terminato perché il EnableRaisingEvents proprietà è stata impostata durante il processo è stato creato.It raises the Exited event when the process exits because the EnableRaisingEvents property was set when the process was created. Il Exited gestore dell'evento Visualizza le informazioni sul processo.The Exited event handler displays process information.

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

class PrintProcessClass
{
    private Process myProcess;
    private int elapsedTime;
    private bool eventHandled;

    // Print a file with any known extension.
    public void PrintDoc(string fileName)
    {
        elapsedTime = 0;
        eventHandled = false;

        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.
            const int SleepAmount = 100;
            while (!eventHandled)
            {
                elapsedTime += SleepAmount;
                if (elapsedTime > 30000)
                {
                    break;
                }
                
                Thread.Sleep(SleepAmount);
            }
        }
    }

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

    public static void 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();
        myPrintProcess.PrintDoc(args[0]);
    }
}
Imports System
Imports System.Diagnostics
Imports System.Threading

Class PrintProcessClass

    Private WithEvents myProcess As Process
    Private elapsedTime As Integer
    Private eventHandled As Boolean

    Public Event Exited As EventHandler

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

        elapsedTime = 0
        eventHandled = False

        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.Start()

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

        ' Wait for Exited event, but not more than 30 seconds.
        Const SLEEP_AMOUNT As Integer = 100
        Do While Not eventHandled
            elapsedTime += SLEEP_AMOUNT
            If elapsedTime > 30000 Then
                Exit Do
            End If
            Thread.Sleep(SLEEP_AMOUNT)
        Loop
    End Sub

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

        eventHandled = True
        Console.WriteLine("Exit time:    {0}" & vbCrLf &
            "Exit code:    {1}" & vbCrLf & "Elapsed time: {2}",
            myProcess.ExitTime, myProcess.ExitCode, elapsedTime)
    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))
    End Sub
End Class

Commenti

Il Exited evento indica che il processo associato è stato chiuso.The Exited event indicates that the associated process exited. Questo evento indica che il processo di terminazione (interrotto) o è stato chiuso.This occurrence means either that the process terminated (aborted) or successfully closed. Questo evento può verificarsi solo se il valore della EnableRaisingEvents è di proprietà true.This event can occur only if the value of the EnableRaisingEvents property is true.

Esistono due modi per visualizzare una notifica quando il processo associato viene chiuso: in modo sincrono e asincrono.There are two ways of being notified when the associated process exits: synchronously and asynchronously. La notifica sincrona si intende chiamare il WaitForExit metodo per bloccare il thread corrente fino alla chiusura del processo.Synchronous notification means calling the WaitForExit method to block the current thread until the process exits. Notifica asincrona Usa le Exited evento, che consente al thread chiamante di continuare l'esecuzione nel frattempo.Asynchronous notification uses the Exited event, which allows the calling thread to continue execution in the meantime. Nel secondo caso EnableRaisingEvents deve essere impostata su true per l'applicazione chiamante riceva l'evento di chiusura.In the latter case, EnableRaisingEvents must be set to true for the calling application to receive the Exited event.

Quando il sistema operativo viene arrestato un processo, notifica a tutti gli altri processi che hanno registrato i gestori dell'evento di chiusura.When the operating system shuts down a process, it notifies all other processes that have registered handlers for the Exited event. A questo punto, l'handle del processo che semplicemente è stato chiuso può essere utilizzato per accedere a alcune proprietà, ad esempio ExitTime e HasExited che il sistema operativo gestisce fino a quando non rilascia completamente tale handle.At this time, the handle of the process that just exited can be used to access some properties such as ExitTime and HasExited that the operating system maintains until it releases that handle completely.

Nota

Anche se si dispone di un handle a un processo è ancora terminato, non è possibile chiamare Start per ristabilire la connessione allo stesso processo.Even if you have a handle to an exited process, you cannot call Start again to reconnect to the same process. La chiamata Start automaticamente rilascia il processo associato e si connette a un processo con lo stesso file, ma un innovativo Handle.Calling Start automatically releases the associated process and connects to a process with the same file but an entirely new Handle.

Per altre informazioni sull'uso del Exited eventi nelle applicazioni Windows Forms, vedere il SynchronizingObject proprietà.For more information about the use of the Exited event in Windows Forms applications, see the SynchronizingObject property.

Sicurezza

LinkDemand
per un'attendibilità totale per il chiamante immediato.for full trust for the immediate caller. Impossibile utilizzare questo membro in codice parzialmente attendibile.This member cannot be used by partially trusted code.

Si applica a