Process.EnableRaisingEvents 속성

정의

프로세스가 종료될 때 Exited 이벤트를 발생시켜야 하는지를 나타내는 값을 가져오거나 설정합니다.

public:
 property bool EnableRaisingEvents { bool get(); void set(bool value); };
public bool EnableRaisingEvents { get; set; }
[System.ComponentModel.Browsable(false)]
public bool EnableRaisingEvents { get; set; }
member this.EnableRaisingEvents : bool with get, set
[<System.ComponentModel.Browsable(false)>]
member this.EnableRaisingEvents : bool with get, set
Public Property EnableRaisingEvents As Boolean

속성 값

종료 명령 또는 Kill() 호출을 통해 연결된 프로세스가 종료될 때 Exited 이벤트가 발생해야 한다면 true이고, 그러지 않으면 false입니다. 기본값은 false입니다. 값 EnableRaisingEventsfalse이 인 Exited 경우에도 프로세스가 종료되었다고 HasExited 판단되면 속성 접근자가 이벤트를 발생합니다.

특성

예제

다음 코드 예제에서는 파일을 인쇄하는 프로세스를 만듭니다. 프로세스가 종료될 때 이벤트가 발생 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

설명

속성은 EnableRaisingEvents 운영 체제가 프로세스를 종료할 때 구성 요소에 알림을 받아야 하는지 여부를 제안합니다. EnableRaisingEvents 프로세스를 종료 하는 애플리케이션에 알리기 위해 속성은 비동기 처리에 사용 합니다. 강제 종료 이벤트 (종료 이벤트가 발생 될 때까지 애플리케이션의 프로세스를 중단)에 대 한 동기적으로 대기 하는 애플리케이션을 사용 하는 WaitForExit 메서드.

참고

Visual Studio를 사용하고 프로젝트에서 Exited 구성 요소를 두 번 클릭하면 Process 이벤트 대리자 및 이벤트 처리기가 자동으로 생성됩니다. 추가 코드는 속성을 falseEnableRaisingEvents 설정합니다. 연결된 프로세스가 종료될 때 이벤트 처리기가 실행되려면 이 속성을 true 로 변경해야 합니다.

구성 요소의 EnableRaisingEvents 값이 true이거나 EnableRaisingEvents 가 이 falseHasExited 구성 요소가 검사 호출되는 경우 구성 요소는 운영 체제에 의해 저장된 상태로 유지되는 연결된 프로세스에 대한 관리 정보에 액세스할 수 있습니다. 이러한 정보에는 및 가 ExitTime 포함됩니다 ExitCode.

연결된 프로세스가 종료되면 구성 요소의 가 Handle 더 이상 기존 프로세스 리소스를 가리키지 않습니다. 대신 프로세스 리소스에 대한 운영 체제 정보에 액세스하는 데만 사용할 수 있습니다. 운영 체제는 구성 요소에서 릴리스되지 않은 종료된 프로세스에 Process 대한 핸들이 있으므로 및 Handle 정보를 메모리에 유지 ExitTime 합니다.

프로세스가 종료되는 것을 감시하는 것과 관련된 비용이 있습니다. 가 이 trueExitedEnableRaisingEvents 연결된 프로세스가 종료될 때 이벤트가 발생합니다. 이벤트에 대한 프로시저는 Exited 해당 시간에 실행됩니다.

경우에 따라 애플리케이션 프로세스를 시작 하지만 종료 되는 알림이 필요 하지 않습니다. 예를 들어, 애플리케이션 사용자가 텍스트 편집을 수행 하지만 더 이상 하 게 메모장 애플리케이션을 사용 하도록 허용 하려면 메모장을 시작 수 있습니다. 애플리케이션의 지속적인된 작업에 관련 되지 않기 때문에 프로세스가 종료 될 때 알림을 방지할 수 있습니다. 를 로 설정 EnableRaisingEvents 하면 false 시스템 리소스를 저장할 수 있습니다.

적용 대상

추가 정보