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

属性值

Boolean

如果关联的进程终止(通过退出或者调用true )时应引发 Exited 事件,则为 Kill();否则为 false。 默认值为 false。 请注意,Exited即使EnableRaisingEventsfalse进程在过程中或用户执行HasExited检查之前退出,也会引发该事件。

属性

示例

下面的代码示例创建一个打印文件的进程。 它设置属性 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]);
    }
}
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 并双击项目中的 Process 组件, Exited 则自动生成事件委托和事件处理程序。 其他代码将 EnableRaisingEvents 属性设置为 false. 必须将此属性 true 更改为使事件处理程序在关联进程退出时执行。

如果组件 EnableRaisingEvents 的值为 true或组件调用检查时间 EnableRaisingEvents false HasExited ,则组件可以访问关联进程的管理信息,该信息仍由操作系统存储。 此类信息包括 ExitTimeExitCode

关联进程退出后, Handle 组件不再指向现有进程资源。 相反,它只能用于访问操作系统有关进程资源的信息。 操作系统请注意,组件尚未释放Process的退出进程有句柄,因此它会将和Handle信息保留在ExitTime内存中。

存在与监视进程退出相关的成本。 true如果是EnableRaisingEvents,则Exited当关联进程终止时引发该事件。 此时事件运行的过程 Exited

有时,应用程序会启动一个进程,但不需要通知其关闭。 例如,应用程序可以启动记事本以允许用户执行文本编辑,但不会进一步使用记事本应用程序。 可以选择在进程退出时避免通知,因为它与应用程序的继续操作无关。 设置为EnableRaisingEventsfalse可以保存系统资源。

适用于

另请参阅