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 연결된 프로세스가 종료되었음을 나타냅니다. 이 발생은 프로세스가 종료되었거나(중단됨) 성공적으로 닫혔다는 것을 의미합니다. 이 이벤트는 속성 값 EnableRaisingEvents 이 인 경우에만 발생할 수 있습니다 true.

연결된 프로세스가 종료될 때 알림을 받는 방법에는 동기 및 비동기식이라는 두 가지 방법이 있습니다. 동기 알림은 프로세스가 종료될 때까지 메서드를 WaitForExit 호출하여 현재 스레드를 차단하는 것을 의미합니다. 비동기 알림은 호출 스레드가 Exited 그 동안 실행을 계속할 수 있도록 하는 이벤트를 사용합니다. 후자의 경우 EnableRaisingEvents 로 설정 되어야 합니다 true 호출 애플리케이션이 종료 되었습니다. 이벤트를 수신 합니다.

운영 체제가 프로세스를 종료하면 Exited 이벤트에 대한 처리기를 등록한 다른 모든 프로세스에 알 수 있습니다. 이때 방금 종료된 프로세스의 핸들을 사용하여 과 같은 ExitTime 일부 속성에 액세스하고 HasExited 운영 체제가 완전히 처리되는 프로세스를 해제할 때까지 유지 관리할 수 있습니다.

참고

종료된 프로세스에 대한 핸들이 있더라도 를 다시 호출 Start 하여 동일한 프로세스에 다시 연결할 수 없습니다. 를 호출하면 Start 연결된 프로세스가 자동으로 해제되고 완전히 새로운 Handle파일인 프로세스에 연결됩니다.

사용에 대 한 자세한 합니다 Exited Windows Forms 애플리케이션에서 이벤트 참조를 SynchronizingObject 속성입니다.

적용 대상