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 、関連付けられたプロセスが終了したことを示します。 この発生は、プロセスが終了 (中止) したか、正常に閉じられたことを意味します。 このイベントは、 プロパティtrueEnableRaisingEvents値が の場合にのみ発生します。

関連付けられたプロセスが終了したときに通知を受け取る方法は、同期と非同期の 2 つあります。 同期通知とは、 メソッドを WaitForExit 呼び出して、プロセスが終了するまで現在のスレッドをブロックすることを意味します。 非同期通知では、 イベントを Exited 使用します。これにより、呼び出し元のスレッドはそれまでの間に実行を続行できます。 後者の場合、 EnableRaisingEvents 呼び出し元のアプリケーションが Exited イベントを受信するには、 を に true 設定する必要があります。

オペレーティング システムは、プロセスをシャットダウンすると、Exited イベントのハンドラーが登録されている他のすべてのプロセスに通知します。 現時点では、終了したプロセスのハンドルを使用して、 などの ExitTime 一部のプロパティにアクセスし HasExited 、オペレーティング システムが完全に処理を解放するまで維持することができます。

注意

終了したプロセスへのハンドルがある場合でも、再度 を呼び出 Start して同じプロセスに再接続することはできません。 を呼び出すと Start 、関連付けられたプロセスが自動的に解放され、同じファイルがまったく新しい Handleプロセスに接続されます。

Windows フォーム アプリケーションでの イベントのExited使用の詳細については、 プロパティをSynchronizingObject参照してください。

適用対象