Process.Exited 事件

定義

發生於處理序結束時。

C#
public event EventHandler Exited;

事件類型

範例

下列程式代碼範例會建立列印檔案的程式。 當進程結束時,它會引發 Exited 事件,因為 EnableRaisingEvents 建立進程時已設定 屬性。 Exited事件處理程式會顯示進程資訊。

C#
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]);
    }
}

備註

事件 Exited 表示相關聯的進程已結束。 發生此情況表示進程終止 (中止) 或已成功關閉。 只有當 屬性值為 trueEnableRaisingEvents,才會發生這個事件。

當相關聯的進程結束時,有兩種方式可以收到通知:同步和異步。 同步通知表示呼叫 WaitForExit 方法來封鎖目前的線程,直到進程結束為止。 異步通知會使用 Exited 事件,這可讓呼叫線程同時繼續執行。 在後者的情況下,必須設定true為 ,EnableRaisingEvents呼叫端應用程式才能接收 Exited 事件。

當操作系統關閉進程時,它會通知已針對 Exited 事件註冊處理程式的所有其他進程。 此時,剛結束的進程句柄可用來存取某些屬性,例如 ExitTime ,而且 HasExited 操作系統會維護,直到它完全釋放該句柄為止。

備註

即使您有已結束進程的句柄,您也無法再次呼叫 以重新連線 Start 到相同的進程。 呼叫 Start 會自動釋放相關聯的進程,並使用相同的檔案連接到進程,但全新的 Handle

如需在 Windows Forms 應用程式中使用 Exited 事件的詳細資訊,請參閱 SynchronizingObject 屬性。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1