Process.Exited Événement
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Se produit lorsqu’un processus se ferme.
public:
event EventHandler ^ Exited;
public event EventHandler Exited;
member this.Exited : EventHandler
Public Custom Event Exited As EventHandler
Type d'événement
Exemples
L’exemple de code suivant crée un processus qui imprime un fichier. Elle déclenche l’événement Exited lorsque le processus se termine, car la EnableRaisingEvents propriété a été définie lors de la création du processus. Le Exited gestionnaire d’événements affiche les informations de processus.
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]);
}
}
open System
open System.Diagnostics
open System.Threading.Tasks
let mutable myProcess = new Process()
let mutable eventHandled = TaskCompletionSource<bool>()
// Handle Exited event and display process information.
let myProcess_Exited (sender: obj) (e: EventArgs) =
printfn $"Exit time : {myProcess.ExitTime}\n"
printfn $"Exit code : {myProcess.ExitCode}\n"
printfn $"Elapsed time : {round ((myProcess.ExitTime - myProcess.StartTime).TotalMilliseconds)}"
eventHandled.TrySetResult true |> ignore
// Print a file with any known extension.
let printDoc fileName =
task {
eventHandled <- TaskCompletionSource<bool>()
use 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.AddHandler(EventHandler myProcess_Exited)
myProcess.Start() |> ignore
with ex ->
printfn $"An error occurred trying to print \"{fileName}\":\n{ex.Message}"
// Wait for Exited event, but not more than 30 seconds.
let! _ = Task.WhenAny(eventHandled.Task, Task.Delay(30000))
()
}
[<EntryPoint>]
let main args =
// Verify that an argument has been entered.
if args.Length <= 0 then
printfn "Enter a file name."
else
// Create the process and print the document.
printDoc(args[0]).Wait() |> ignore
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
Remarques
L’événement Exited indique que le processus associé s’est arrêté. Cette occurrence signifie que le processus s’est arrêté (abandonné) ou fermé avec succès. Cet événement ne peut se produire que si la valeur de la EnableRaisingEvents propriété est true.
Il existe deux façons d’être averti lorsque le processus associé quitte : de façon synchrone et asynchrone. La notification synchrone signifie appeler la WaitForExit méthode pour bloquer le thread actuel jusqu’à ce que le processus se termine. La notification asynchrone utilise l’événement Exited , ce qui permet au thread appelant de continuer l’exécution en attendant. Dans ce dernier cas, EnableRaisingEvents doit être défini sur true pour que l’application appelante reçoive l’événement Exited.
Lorsque le système d’exploitation arrête un processus, il avertit tous les autres processus qui ont inscrit des gestionnaires pour l’événement Exited. À ce stade, le handle du processus qui vient de quitter peut être utilisé pour accéder à certaines propriétés telles que ExitTime et HasExited que le système d’exploitation conserve jusqu’à ce qu’il libère complètement.
Note
Même si vous avez un handle vers un processus sortant, vous ne pouvez pas appeler Start à nouveau pour vous reconnecter au même processus. L’appel Start libère automatiquement le processus associé et se connecte à un processus avec le même fichier, mais un tout nouveau Handle.
Pour plus d’informations sur l’utilisation de l’événement Exited dans les applications Windows Forms, consultez la SynchronizingObject propriété.