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

屬性值

如果應該在相關聯處理序終止時引發 Exited 事件 (經由結束或呼叫 Kill()),則為 true,否則為 false。 預設為 false。 請注意,即使的值為 EnableRaisingEventsfalseExited 如果 事件判斷進程已結束,事件也會由 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,或 當 是 falseHasExited元件叫用檢查時EnableRaisingEvents,元件就可以存取相關聯進程的系統管理資訊,該進程仍會由操作系統儲存。 這類資訊包括 ExitTimeExitCode

在相關聯的進程結束之後, Handle 元件的 不再指向現有的進程資源。 相反地,它只能用來存取操作系統有關進程資源的資訊。 操作系統知道有一個句柄可供元件釋放Process的已結束進程,因此會將 和 Handle 資訊保留在ExitTime記憶體中。

有一個與監看程序結束相關的成本。 如果 為 EnableRaisingEventstrue,當相關聯的進程終止時,就會 Exited 引發 事件。 您當時執行 Exited 事件的程式。

有時候,您的應用程式會啟動程式,但不需要通知其關閉。 例如,您的應用程式可以啟動 [記事本] 以允許使用者執行文字編輯,但不會進一步使用 [記事本] 應用程式。 您可以選擇避免程序結束時收到通知,因為它與應用程式的繼續作業無關。 將設定 EnableRaisingEventsfalse 可以儲存系統資源。

適用於

另請參閱