Process.Exited 事件

定義

發生於處理序結束時。

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

事件類型

範例

下列程式碼範例會建立列印檔案的程式。 它會在進程結束時引發 Exited 事件, EnableRaisingEvents 因為建立進程時已設定 屬性。 Exited事件處理常式會顯示進程資訊。

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

備註

事件 Exited 表示相關聯的進程已結束。 此情況表示進程已終止 (中止) 或成功關閉。 只有當 屬性的值 EnableRaisingEventstrue 時,才會發生這個事件。

當相關聯的進程結束時,有兩種方式可以收到通知:同步和非同步。 同步通知表示呼叫 WaitForExit 方法來封鎖目前的執行緒,直到進程結束為止。 非同步通知會 Exited 使用 事件,這可讓呼叫執行緒同時繼續執行。 在後者的情況下, EnableRaisingEvents 呼叫端應用程式必須設定為 true ,才能接收 Exited 事件。

當作業系統關閉進程時,它會通知所有其他已為 Exited 事件註冊處理常式的進程。 此時,剛結束的進程控制碼可用來存取某些屬性,例如 ExitTimeHasExited 作業系統會維護,直到它完全釋放該控制碼為止。

注意

即使您有已結束進程的控制碼,您也無法再次呼叫 以重新連線 Start 到相同的進程。 呼叫 Start 會自動釋放相關聯的進程,並聯機至具有相同檔案但全新的 Handle 進程。

如需在 Windows Forms 應用程式中使用 Exited 事件的詳細資訊,請參閱 SynchronizingObject 屬性。

適用於