다음을 통해 공유


Process.Exited 이벤트

정의

프로세스가 종료되면 발생합니다.

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

이벤트 유형

예제

다음 코드 예제에서는 파일을 인쇄하는 프로세스를 만듭니다. 프로세스가 생성되었을 때 속성이 설정되었기 때문에 EnableRaisingEvents 프로세스가 종료되면 이벤트가 발생 Exited 합니다. 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]);
    }
}
open System
open System.Diagnostics
open System.Threading.Tasks

let mutable myProcess = new Process()
let mutable eventHandled = TaskCompletionSource<bool>()

// Handle Exited event and display process information.
let myProcess_Exited (sender: obj) (e: EventArgs) =
    printfn $"Exit time    : {myProcess.ExitTime}\n"
    printfn $"Exit code    : {myProcess.ExitCode}\n"
    printfn $"Elapsed time : {round ((myProcess.ExitTime - myProcess.StartTime).TotalMilliseconds)}"
    eventHandled.TrySetResult true |> ignore

// Print a file with any known extension.
let printDoc fileName =
    task {
        eventHandled <- TaskCompletionSource<bool>()

        use 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.AddHandler(EventHandler myProcess_Exited)
            myProcess.Start() |> ignore
        with ex ->
            printfn $"An error occurred trying to print \"{fileName}\":\n{ex.Message}"

        // Wait for Exited event, but not more than 30 seconds.
        let! _ = Task.WhenAny(eventHandled.Task, Task.Delay(30000))
        ()
    }

[<EntryPoint>]
let main args =
    // Verify that an argument has been entered.
    if args.Length <= 0 then
        printfn "Enter a file name."
    else
        // Create the process and print the document.
        printDoc(args[0]).Wait() |> ignore

    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 호출 애플리케이션이 Exited 이벤트를 수신하도록 설정 true 해야 합니다.

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

메모

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

Windows Forms 애플리케이션에서 이벤트의 사용에 Exited 대 한 자세한 내용은 속성을 참조 SynchronizingObject 하세요.

적용 대상