Process.ExitCode Właściwość

Definicja

Pobiera wartość określoną przez skojarzony proces po zakończeniu.

public:
 property int ExitCode { int get(); };
public int ExitCode { get; }
[System.ComponentModel.Browsable(false)]
public int ExitCode { get; }
member this.ExitCode : int
[<System.ComponentModel.Browsable(false)>]
member this.ExitCode : int
Public ReadOnly Property ExitCode As Integer

Wartość właściwości

Kod określony przez skojarzony proces po zakończeniu.

Atrybuty

Wyjątki

Proces nie zakończył się.

-lub-

Proces Handle jest nieprawidłowy.

Próbujesz uzyskać dostęp do ExitCode właściwości dla procesu uruchomionego na komputerze zdalnym. Ta właściwość jest dostępna tylko dla procesów uruchomionych na komputerze lokalnym.

Przykłady

Poniższy przykład uruchamia wystąpienie Notatnika. Następnie przykład pobiera i wyświetla różne właściwości skojarzonego procesu. Przykład wykrywa, kiedy proces kończy działanie, i wyświetla kod zakończenia procesu.

#using <system.dll>

using namespace System;
using namespace System::Diagnostics;
int main()
{
   
   // Define variables to track the peak
   // memory usage of the process.
   _int64 peakPagedMem = 0,peakWorkingSet = 0,peakVirtualMem = 0;
   Process^ myProcess = nullptr;
   try
   {
      
      // Start the process.
      myProcess = Process::Start( "NotePad.exe" );
      
      // Display the process statistics until
      // the user closes the program.
      do
      {
         if (  !myProcess->HasExited )
         {
            
            // Refresh the current process property values.
            myProcess->Refresh();
            Console::WriteLine();
            
            // Display current process statistics.
            Console::WriteLine( "{0} -", myProcess );
            Console::WriteLine( "-------------------------------------" );
            Console::WriteLine( "  physical memory usage: {0}", myProcess->WorkingSet64 );
            Console::WriteLine( "  base priority: {0}", myProcess->BasePriority );
            Console::WriteLine( "  priority class: {0}", myProcess->PriorityClass );
            Console::WriteLine( "  user processor time: {0}", myProcess->UserProcessorTime );
            Console::WriteLine( "  privileged processor time: {0}", myProcess->PrivilegedProcessorTime );
            Console::WriteLine( "  total processor time: {0}", myProcess->TotalProcessorTime );
            Console::WriteLine("  PagedSystemMemorySize64: {0}", myProcess->PagedSystemMemorySize64);
            Console::WriteLine("  PagedMemorySize64: {0}", myProcess->PagedMemorySize64);
            
            // Update the values for the overall peak memory statistics.
            peakPagedMem = myProcess->PeakPagedMemorySize64;
            peakVirtualMem = myProcess->PeakVirtualMemorySize64;
            peakWorkingSet = myProcess->PeakWorkingSet64;
            if ( myProcess->Responding )
            {
               Console::WriteLine( "Status = Running" );
            }
            else
            {
               Console::WriteLine( "Status = Not Responding" );
            }
         }
      }
      while (  !myProcess->WaitForExit( 1000 ) );
      Console::WriteLine();
      Console::WriteLine( "Process exit code: {0}", myProcess->ExitCode );
      
      // Display peak memory statistics for the process.
      Console::WriteLine( "Peak physical memory usage of the process: {0}", peakWorkingSet );
      Console::WriteLine( "Peak paged memory usage of the process: {0}", peakPagedMem );
      Console::WriteLine( "Peak virtual memory usage of the process: {0}", peakVirtualMem );
   }
   finally
   {
      if ( myProcess != nullptr )
      {
         myProcess->Close();
      }
   }

}
using System;
using System.Diagnostics;

namespace ProcessSample
{
    class ProcessMonitorSample
    {
        public static void Main()
        {
            // Define variables to track the peak
            // memory usage of the process.
            long peakPagedMem   = 0,
                 peakWorkingSet = 0,
                 peakVirtualMem = 0;

            // Start the process.
            using (Process myProcess = Process.Start("NotePad.exe"))
            {
                // Display the process statistics until
                // the user closes the program.
                do
                {
                    if (!myProcess.HasExited)
                    {
                        // Refresh the current process property values.
                        myProcess.Refresh();

                        Console.WriteLine();

                        // Display current process statistics.

                        Console.WriteLine($"{myProcess} -");
                        Console.WriteLine("-------------------------------------");

                        Console.WriteLine($"  Physical memory usage     : {myProcess.WorkingSet64}");
                        Console.WriteLine($"  Base priority             : {myProcess.BasePriority}");
                        Console.WriteLine($"  Priority class            : {myProcess.PriorityClass}");
                        Console.WriteLine($"  User processor time       : {myProcess.UserProcessorTime}");
                        Console.WriteLine($"  Privileged processor time : {myProcess.PrivilegedProcessorTime}");
                        Console.WriteLine($"  Total processor time      : {myProcess.TotalProcessorTime}");
                        Console.WriteLine($"  Paged system memory size  : {myProcess.PagedSystemMemorySize64}");
                        Console.WriteLine($"  Paged memory size         : {myProcess.PagedMemorySize64}");

                        // Update the values for the overall peak memory statistics.
                        peakPagedMem   = myProcess.PeakPagedMemorySize64;
                        peakVirtualMem = myProcess.PeakVirtualMemorySize64;
                        peakWorkingSet = myProcess.PeakWorkingSet64;

                        if (myProcess.Responding)
                        {
                            Console.WriteLine("Status = Running");
                        }
                        else
                        {
                            Console.WriteLine("Status = Not Responding");
                        }
                    }
                }
                while (!myProcess.WaitForExit(1000));

                Console.WriteLine();
                Console.WriteLine($"  Process exit code          : {myProcess.ExitCode}");

                // Display peak memory statistics for the process.
                Console.WriteLine($"  Peak physical memory usage : {peakWorkingSet}");
                Console.WriteLine($"  Peak paged memory usage    : {peakPagedMem}");
                Console.WriteLine($"  Peak virtual memory usage  : {peakVirtualMem}");
            }
        }
    }
}
Imports System.Diagnostics

Namespace ProcessSample
    Class ProcessMonitorSample

        Public Shared Sub Main()

            ' Define variables to track the peak
            ' memory usage of the process.
            Dim peakPagedMem As Long = 0
            Dim peakWorkingSet As Long = 0
            Dim peakVirtualMem As Long = 0

            ' Start the process.
            Using myProcess = Process.Start("NotePad.exe")

                ' Display process statistics until
                ' the user closes the program.
                Do

                    If Not myProcess.HasExited Then

                        ' Refresh the current process property values.
                        myProcess.Refresh()

                        Console.WriteLine()

                        ' Display current process statistics.

                        Console.WriteLine($"{myProcess} -")
                        Console.WriteLine("-------------------------------------")

                        Console.WriteLine($"  Physical memory usage     : {myProcess.WorkingSet64}")
                        Console.WriteLine($"  Base priority             : {myProcess.BasePriority}")
                        Console.WriteLine($"  Priority class            : {myProcess.PriorityClass}")
                        Console.WriteLine($"  User processor time       : {myProcess.UserProcessorTime}")
                        Console.WriteLine($"  Privileged processor time : {myProcess.PrivilegedProcessorTime}")
                        Console.WriteLine($"  Total processor time      : {myProcess.TotalProcessorTime}")
                        Console.WriteLine($"  Paged system memory size  : {myProcess.PagedSystemMemorySize64}")
                        Console.WriteLine($"  Paged memory size         : {myProcess.PagedMemorySize64}")

                        ' Update the values for the overall peak memory statistics.
                        peakPagedMem = myProcess.PeakPagedMemorySize64
                        peakVirtualMem = myProcess.PeakVirtualMemorySize64
                        peakWorkingSet = myProcess.PeakWorkingSet64

                        If myProcess.Responding Then
                            Console.WriteLine("Status = Running")
                        Else
                            Console.WriteLine("Status = Not Responding")
                        End If
                    End If
                Loop While Not myProcess.WaitForExit(1000)

                Console.WriteLine()
                Console.WriteLine($"  Process exit code                         : {myProcess.ExitCode}")

                ' Display peak memory statistics for the process.
                Console.WriteLine($"  Peak physical memory usage of the process : {peakWorkingSet}")
                Console.WriteLine($"  Peak paged memory usage of the process    : {peakPagedMem}")
                Console.WriteLine($"  Peak virtual memory usage of the process  : {peakVirtualMem}")
            End Using
        End Sub
    End Class
End Namespace

Uwagi

Użyj ExitCode polecenia , aby uzyskać stan zwrócony przez proces systemowy po jego zakończeniu. Możesz użyć kodu zakończenia, podobnie jak wartość zwracana main() przez liczbę całkowitą z procedury.

Wartość ExitCode procesu odzwierciedla konkretną konwencję zaimplementowaną przez dewelopera aplikacji dla tego procesu. Jeśli używasz wartości kodu zakończenia do podejmowania decyzji w kodzie, upewnij się, że znasz konwencję kodu zakończenia używaną przez proces aplikacji.

Deweloperzy zwykle wskazują pomyślne zakończenie przez ExitCode wartość zero i wyznaczać błędy według wartości niezerowych, których metoda wywołująca może użyć do zidentyfikowania przyczyny nieprawidłowego zakończenia procesu. Nie jest konieczne przestrzeganie tych wytycznych, ale są one konwencją.

Jeśli spróbujesz uzyskać wartość ExitCode przed zakończeniem procesu, próba zgłosi wyjątek. Najpierw sprawdź właściwość, HasExited aby sprawdzić, czy skojarzony proces został zakończony.

Uwaga

Gdy standardowe dane wyjściowe zostały przekierowane do asynchronicznych procedur obsługi zdarzeń, możliwe, że przetwarzanie danych wyjściowych nie zostanie ukończone po HasExited zwrócenie wartości true. Aby upewnić się, że obsługa zdarzeń asynchronicznych została ukończona, przed sprawdzeniem HasExitedwywołaj WaitForExit() przeciążenie, które nie przyjmuje parametru .

Możesz użyć CloseMainWindow metody lub Kill , aby spowodować zakończenie skojarzonego procesu.

Istnieją dwa sposoby powiadamiania o zakończeniu skojarzonego procesu: synchronicznie i asynchronicznie. Powiadomienie synchroniczne polega na wywołaniu WaitForExit metody w celu wstrzymania przetwarzania aplikacji do momentu zakończenia skojarzonego składnika. Powiadomienie asynchroniczne opiera się na Exited zdarzeniu. W przypadku korzystania z powiadomienia EnableRaisingEvents asynchronicznego należy ustawić true wartość , Process aby składnik odbierał powiadomienie o zakończeniu procesu.

Dotyczy

Zobacz też