Process.EnableRaisingEvents Propriedade

Definição

Obtém ou define se o evento Exited deve ser gerado quando o processo é encerrado.Gets or sets whether the Exited event should be raised when the process terminates.

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

Valor da propriedade

Boolean

true se o evento Exited precisar ser gerado quando o processo associado for terminado (por meio de uma saída ou uma chamada a Kill()); caso contrário, false.true if the Exited event should be raised when the associated process is terminated (through either an exit or a call to Kill()); otherwise, false. O padrão é false.The default is false. Observe que o Exited evento é gerado mesmo se o valor de EnableRaisingEvents for false quando o processo for encerrado durante ou antes de o usuário executar uma HasExited verificação.Note that the Exited event is raised even if the value of EnableRaisingEvents is false when the process exits during or before the user performs a HasExited check.

Atributos

Exemplos

O exemplo de código a seguir cria um processo que imprime um arquivo.The following code example creates a process that prints a file. Ele define a EnableRaisingEvents propriedade para fazer com que o processo gere o Exited evento quando ele é encerrado.It sets the EnableRaisingEvents property to cause the process to raise the Exited event when it exits. O Exited manipulador de eventos exibe informações de processo.The Exited event handler displays process information.

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

Comentários

A EnableRaisingEvents propriedade sugere se o componente deve ser notificado quando o sistema operacional desligar um processo.The EnableRaisingEvents property suggests whether the component should be notified when the operating system has shut down a process. A EnableRaisingEvents propriedade é usada no processamento assíncrono para notificar o aplicativo de que um processo foi encerrado.The EnableRaisingEvents property is used in asynchronous processing to notify your application that a process has exited. Para forçar seu aplicativo a esperar de forma síncrona um evento de saída (que interrompe o processamento do aplicativo até que o evento de saída tenha ocorrido), use o WaitForExit método.To force your application to synchronously wait for an exit event (which interrupts processing of the application until the exit event has occurred), use the WaitForExit method.

Observação

Se você estiver usando o Visual Studio e clicar duas vezes em um Process componente em seu projeto, um Exited representante de evento e um manipulador de eventos serão gerados automaticamente.If you're using Visual Studio and double-click a Process component in your project, an Exited event delegate and event handler are automatically generated. O código adicional define a EnableRaisingEvents propriedade como false .Additional code sets the EnableRaisingEvents property to false. Você deve alterar essa propriedade para true para que seu manipulador de eventos seja executado quando o processo associado for encerrado.You must change this property to true for your event handler to execute when the associated process exits.

Se o valor do componente EnableRaisingEvents for true , ou quando EnableRaisingEvents for false e uma HasExited verificação for invocada pelo componente, o componente poderá acessar as informações administrativas para o processo associado, que permanece armazenado pelo sistema operacional.If the component's EnableRaisingEvents value is true, or when EnableRaisingEvents is false and a HasExited check is invoked by the component, the component can access the administrative information for the associated process, which remains stored by the operating system. Essas informações incluem o ExitTime e o ExitCode .Such information includes the ExitTime and the ExitCode.

Depois que o processo associado é encerrado, o Handle do componente não aponta mais para um recurso de processo existente.After the associated process exits, the Handle of the component no longer points to an existing process resource. Em vez disso, ele só pode ser usado para acessar as informações do sistema operacional sobre o recurso do processo.Instead, it can only be used to access the operating system's information about the process resource. O sistema operacional está ciente de que há identificadores para sair de processos que não foram lançados por Process componentes, portanto, ele mantém as ExitTime Handle informações e na memória.The operating system is aware that there are handles to exited processes that haven't been released by Process components, so it keeps the ExitTime and Handle information in memory.

Há um custo associado à observação de um processo para sair.There's a cost associated with watching for a process to exit. Se EnableRaisingEvents for true , o Exited evento será gerado quando o processo associado for encerrado.If EnableRaisingEvents is true, the Exited event is raised when the associated process terminates. Os procedimentos para o Exited evento são executados nesse momento.Your procedures for the Exited event run at that time.

Às vezes, seu aplicativo inicia um processo, mas não requer notificação de seu fechamento.Sometimes, your application starts a process but doesn't require notification of its closure. Por exemplo, seu aplicativo pode iniciar o bloco de notas para permitir que o usuário execute a edição de texto, mas não faça mais uso do aplicativo do bloco de notas.For example, your application can start Notepad to allow the user to perform text editing but make no further use of the Notepad application. Você pode optar por evitar a notificação quando o processo é encerrado porque não é relevante para a operação contínua do seu aplicativo.You can choose to avoid notification when the process exits because it's not relevant to the continued operation of your application. EnableRaisingEventsA configuração para false pode salvar recursos do sistema.Setting EnableRaisingEvents to false can save system resources.

Aplica-se a

Confira também