Process.Exited Zdarzenie

Definicja

Występuje po zakończeniu procesu.

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

Typ zdarzenia

Przykłady

Poniższy przykład kodu tworzy proces, który drukuje plik. Zgłasza zdarzenie po zakończeniu Exited procesu, ponieważ EnableRaisingEvents właściwość została ustawiona podczas tworzenia procesu. Program Exited obsługi zdarzeń wyświetla informacje o procesie.

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

Uwagi

Zdarzenie Exited wskazuje, że skojarzony proces zakończył działanie. To zdarzenie oznacza, że proces został zakończony (przerwany) lub pomyślnie zamknięty. To zdarzenie może wystąpić tylko wtedy, gdy wartość EnableRaisingEvents właściwości to true.

Istnieją dwa sposoby powiadamiania o zakończeniu skojarzonego procesu: synchronicznie i asynchronicznie. Powiadomienie synchroniczne oznacza wywołanie WaitForExit metody w celu zablokowania bieżącego wątku do momentu zakończenia procesu. Powiadomienie asynchroniczne używa Exited zdarzenia, które umożliwia wątek wywołujący kontynuowanie wykonywania w międzyczasie. W tym drugim przypadku należy ustawić true wartość na , EnableRaisingEvents aby aplikacja wywołująca odbierała zdarzenie Exited.

Gdy system operacyjny zamknie proces, powiadamia wszystkie inne procesy, które zarejestrowały programy obsługi dla zdarzenia Exited. W tej chwili dojście do procesu, który właśnie zakończył działanie, może służyć do uzyskiwania dostępu do niektórych właściwości, takich jak ExitTime i HasExited że system operacyjny utrzymuje się, dopóki nie zostanie całkowicie zwolniona.

Uwaga

Nawet jeśli masz dojście do zakończonego procesu, nie można wywołać Start ponownie, aby ponownie nawiązać połączenie z tym samym procesem. Wywołanie Start automatycznie zwalnia skojarzony proces i nawiązuje połączenie z procesem z tym samym plikiem, ale całkowicie nowym Handle.

Aby uzyskać więcej informacji na temat używania Exited zdarzenia w aplikacjach Windows Forms, zobacz SynchronizingObject właściwość .

Dotyczy