Process.EnableRaisingEvents Propiedad

Definición

Obtiene o establece si el evento Exited debe provocarse cuando termine el proceso.

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 de propiedad

Es true si el evento Exited debe provocarse cuando termine el proceso asociado (al salir o al llamar a Kill()); de lo contrario, es false. De manera predeterminada, es false. Tenga en cuenta que, incluso si el valor de EnableRaisingEvents es false, el descriptor de acceso de propiedad generará HasExited el Exited evento , si determina que el proceso se ha cerrado.

Atributos

Ejemplos

En el ejemplo de código siguiente se crea un proceso que imprime un archivo. Establece la EnableRaisingEvents propiedad para que el proceso genere el Exited evento cuando se cierra. El Exited controlador de eventos muestra información del proceso.

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

Comentarios

La EnableRaisingEvents propiedad sugiere si se debe notificar al componente cuando el sistema operativo ha cerrado un proceso. La EnableRaisingEvents propiedad se usa en el procesamiento asincrónico para notificar a la aplicación que se ha cerrado un proceso. Para forzar que la aplicación espere sincrónicamente a un evento de salida (que interrumpe el procesamiento de la aplicación hasta que se haya producido el evento exit), use el WaitForExit método .

Nota

Si usa Visual Studio y hace doble clic en un Process componente del proyecto, se genera automáticamente un Exited delegado de eventos y un controlador de eventos. El código adicional establece la EnableRaisingEvents propiedad en false. Debe cambiar esta propiedad a true para que el controlador de eventos se ejecute cuando se cierre el proceso asociado.

Si el valor del EnableRaisingEvents componente es true, o cuando EnableRaisingEvents es false y el componente invoca una HasExited comprobación, el componente puede tener acceso a la información administrativa del proceso asociado, que permanece almacenada por el sistema operativo. Esta información incluye y ExitTime .ExitCode

Una vez que se cierra el proceso asociado, el Handle del componente ya no apunta a un recurso de proceso existente. En su lugar, solo se puede usar para acceder a la información del sistema operativo sobre el recurso de proceso. El sistema operativo es consciente de que hay identificadores para los procesos salidos que no han sido liberados por Process los componentes, por lo que mantiene la ExitTime información y Handle en la memoria.

Hay un costo asociado con la inspección de un proceso para salir. Si EnableRaisingEvents es true, el Exited evento se genera cuando finaliza el proceso asociado. Los procedimientos para la ejecución del Exited evento en ese momento.

A veces, la aplicación inicia un proceso, pero no requiere notificación de su cierre. Por ejemplo, la aplicación puede iniciar el Bloc de notas para permitir que el usuario realice la edición de texto, pero no use aún más la aplicación bloc de notas. Puede optar por evitar la notificación cuando se cierre el proceso porque no es relevante para el funcionamiento continuado de la aplicación. Establecer EnableRaisingEvents en false puede guardar los recursos del sistema.

Se aplica a

Consulte también