System.Diagnostics.Process Class

Assembly: System.dll
Namespace: System.Diagnostics
Summary
Provides access to local and remote processes and enables you to start and stop local system processes.
C# Syntax:
public class Process : Component
Remarks
A Process component provides access to a process that is running on a computer. A process, in the simplest terms, is a running application. A thread is the basic unit to which the operating system allocates processor time. A thread can execute any part of the code of the process, including parts currently being executed by another thread.

The Process component is a useful tool for starting, stopping, controlling, and monitoring applications. Using the Process component, you can obtain a list of the processes that are running or start a new process. A Process component is used to access system processes. After a Process component has been initialized, it can be used to obtain information about the running process. Such information includes the set of threads, the loaded modules (.dll and .exe files), and performance information such as the amount of memory the process is using.

The process component obtains information about a group of properties all at once. After the Process component has obtained information about one member of any group, it will cache the values for the other properties in that group and not obtain new information about the other members of the group until you call the Process.Refresh method. Therefore, a property value is not guaranteed to be any newer than the last call to the Process.Refresh method. The group breakdowns are operating-system dependent.

A system process is uniquely identified on the system by its process identifier. Like many Windows resources, a process is also identified by its handle, which might not be unique on the computer. A handle is the generic term for an identifier of a resource. The operating system persists the process handle, which is accessed through the Process.Handle property of the Process component, even when the process has exited. Thus, you can get the process's administrative information, such as the Process.ExitCode (usually either zero for success or a nonzero error code) and the Process.ExitTime. Handles are an extremely valuable resource, so leaking handles is more virulent than leaking memory.

See also:
System.Diagnostics Namespace | Process.Start | ProcessStartInfo | System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) | Process.Kill | System.Diagnostics.ProcessThread (not supported on the shared source CLI)

System.Diagnostics.Process Member List:

Public Constructors
ctor #1 Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Initializes a new instance of the Process class.
Public Properties
Container
(inherited from System.ComponentModel.Component)
Read-only

See base class member description: System.ComponentModel.Component.Container


Gets the IContainer that contains the Component.
EnableRaisingEvents Read-write

Gets or sets whether the Process.Exited event should be raised when the process terminates.
ExitCode Read-only

Gets the value that the associated process specified when it terminated.
ExitTime Read-only

Gets the time that the associated process exited.
Handle Read-only

Returns the associated process's native handle.
HasExited Read-only

Gets a value indicating whether the associated process has been terminated.
Id Read-only

Gets the unique identifier for the associated process.
Site
(inherited from System.ComponentModel.Component)
Read-write

See base class member description: System.ComponentModel.Component.Site


Gets or sets the ISite of the Component.
StandardError Read-only

Gets a StreamReader through which to read error output from the application.
StandardInput Read-only

Gets a StreamWriter through which the application can write input to the process.
StandardOutput Read-only

Gets a StreamReader through which the application can read output from the process.
StartInfo Read-write

Gets or sets the properties to pass to the Process.Start method of the Process.
SynchronizingObject Read-write

Gets or sets the object used to marshal the event handler calls that are issued as a result of a process exit event.
Public Methods
Close Frees all the resources that are associated with this component.
CreateObjRef
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.CreateObjRef


Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose
(inherited from System.ComponentModel.Component)
Overloaded:
Dispose()

See base class member description: System.ComponentModel.Component.Dispose


Releases all resources used by the Component.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetCurrentProcess Gets a new Process component and associates it with the currently active process.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.GetLifetimeService


Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
InitializeLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.InitializeLifetimeService


Obtains a lifetime service object to control the lifetime policy for this instance.
Kill Immediately stops the associated process.
Refresh Discards any information about the associated process that has been cached inside the process component.
Start Overloaded:
Start()

Starts (or reuses) the process resource that is specified by the Process.StartInfo property of this Process component and associates it with the component.
Start Overloaded:
Start(ProcessStartInfo startInfo)

Starts the process resource that is specified by the parameter containing process start information (for example, the file name of the process to start) and associates the resource with a new Process component.
Start Overloaded:
Start(string fileName)

Starts a process resource by specifying the name of a document or application file and associates the resource with a new Process component.
Start Overloaded:
Start(string fileName, string arguments)

Starts a process resource by specifying the name of an application and a set of command line arguments, and associates the resource with a new Process component.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
WaitForExit Overloaded:
WaitForExit()

Instructs the Process component to wait indefinitely for the associated process to exit.
WaitForExit Overloaded:
WaitForExit(int milliseconds)

Instructs the Process component to wait the specified number of milliseconds for the associated process to exit.
Public Events
Disposed
(inherited from System.ComponentModel.Component)
See base class member description: System.ComponentModel.Component.Disposed


Adds an event handler to listen to the Component.Disposed event on the component.
Exited Occurs when a process exits.
Protected Properties
DesignMode
(inherited from System.ComponentModel.Component)
Read-only

See base class member description: System.ComponentModel.Component.DesignMode


Gets a value that indicates whether the Component is currently in design mode.
Events
(inherited from System.ComponentModel.Component)
Read-only

See base class member description: System.ComponentModel.Component.Events


Gets the list of event handlers that are attached to this Component.
Protected Methods
Dispose Overloaded:
Dispose(bool disposing)

Overridden:
Supports the Shared Source CLI infrastructure and is not intended to be used directly from your code
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
GetService
(inherited from System.ComponentModel.Component)
See base class member description: System.ComponentModel.Component.GetService


Returns an object that represents a service provided by the Component or by its Container.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.
OnExited Raises the Process.Exited event.

Hierarchy:


System.Diagnostics.Process Member Details

ctor #1
Summary
Initializes a new instance of the Process class.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public Process();
Remarks
If you do not specify the System.Diagnostics.Process.MachineName (not supported on the shared source CLI) property, the default is the local computer, (".").

You have two options for associating a new Process component with a process on the computer. The first option is to use the constructor to create the Process component, set the appropriate members of the Process.StartInfo property and call Process.Start to associate the Process with a new system process. The second option is to associate the Process with a running system process by using System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) or one of the System.Diagnostics.Process.GetProcesses (not supported on the shared source CLI) return values.

If you use a static overload of the Process.Start method to start a new system process, the method creates a new Process component and associates it with the process.

When the ProcessStartInfo.UseShellExecute property is set to its default value, true, you can start applications and documents in a way that is similar to using the Run dialog box of the Windows Start menu. When ProcessStartInfo.UseShellExecute is false, you can start only executables.

Any executable file that you can call from the command line can be started in one of two ways: by setting the appropriate members of the Process.StartInfo property and calling the Process.Start method with no parameters, or by passing the appropriate parameter to the static Process.Start member.

You can create a Process component by using the constructor, one of the static Process.Start overloads, or any of the System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) , System.Diagnostics.Process.GetProcesses (not supported on the shared source CLI) , or System.Diagnostics.Process.GetProcessesByName (not supported on the shared source CLI) methods. After you have done so, you have a view into the associated process. This is not a dynamic view that updates itself automatically when the process properties have changed in memory. Instead, you must call Process.Refresh for the component to update the Process property information in your application.

Return to top


Property: Container (read-only)
Inherited
See base class member description: System.ComponentModel.Component.Container

Summary
Gets the IContainer that contains the Component.
C# Syntax:
public IContainer Container {get;}
Remarks
The components in a container are tracked in a first-in, first-out list, which also defines the order of the components within the container. The last component added is the last component in the list.
See also:
IContainer | Container

Return to top


Property: DesignMode (read-only)
Inherited
See base class member description: System.ComponentModel.Component.DesignMode

Summary
Gets a value that indicates whether the Component is currently in design mode.
C# Syntax:
protected bool DesignMode {get;}
Remarks
The design mode indicator is stored in the ISite; therefore, if the Component does not have an ISite associated with it, this property is always false.
See also:
IContainer | Container | ISite

Return to top


Property: EnableRaisingEvents (read-write)
Summary
Gets or sets whether the Process.Exited event should be raised when the process terminates.
C# Syntax:
public bool EnableRaisingEvents {get; set;}
Remarks
The Process.EnableRaisingEvents property indicates whether the component should be notified when the operating system has shut down a process. The Process.EnableRaisingEvents property is used in asynchronous processing to notify your application that a process has exited. To force your application to synchronously wait for an exit event (which interrupts processing of the application until the exit event has occurred), use the Process.WaitForExit method.

Note If you are using Visual Studio and double-click a Process component in your project, an Process.Exited event delegate and event handler are automatically generated. Additional code sets the Process.EnableRaisingEvents property to false. You must change this property to true for your event handler to be executed when the associated process exits.

When an associated process exits after being shut down by the operation system either through a normal or abnormal termination, the operating system notifies each process component to which the process was associated, as long as the component's Process.EnableRaisingEvents value is true. If a component started the process, the component can then access the administrative information for the associated process, which is still being stored by the operating system. Such information includes the Process.ExitTime, and the Process.ExitCode.

After the associated process exits, the Process.Handle of the component no longer points to an existing process resource. Instead, it can be used only to access the operating system's information about the process resource. The operating system is aware that there are handles to exited processes that have not been released by Process components, so it keeps the Process.ExitTime and Process.Handle information in memory.

There is a cost associated with watching for a process to exit. If Process.EnableRaisingEvents is true, the Process.Exited event is raised when the associated process terminates. The procedures that you have specified for the Process.Exited event run at that time.

Sometimes, your application starts a process but does not need to be notified of its closure. For example, your application can start Notepad to allow the user to perform text editing, but make no further use of the Notepad application. You can choose to not be notified when the process exits, because it is not relevant to the continued operation of your application. Setting Process.EnableRaisingEvents to false saves system resources.

See also:
Process.WaitForExit | Process.Exited | System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) | Process.Kill | Process.Handle | Process.ExitTime | Process.HasExited

Return to top


Property: Events (read-only)
Inherited
See base class member description: System.ComponentModel.Component.Events

Summary
Gets the list of event handlers that are attached to this Component.
C# Syntax:
protected EventHandlerList Events {get;}
Remarks
For more information about handling events, see the conceptual topic at MSDN: eventsoverview.
See also:
EventHandlerList

Return to top


Property: ExitCode (read-only)
Summary
Gets the value that the associated process specified when it terminated.
C# Syntax:
public int ExitCode {get;}
Exceptions
Exception Type Condition
InvalidOperationException The process has not exited.

-or-

The process Process.Handle is not valid.

Remarks
Use Process.ExitCode to get the status that the system process returned when it exited. You can use the exit code much like an integer return value from a main() procedure. How you choose to implement it is specific to your application.

Developers usually indicate a successful exit by an Process.ExitCode value of zero, and designate errors by nonzero values that the calling method can use to identify the cause of an abnormal process termination. It is not necessary to follow these guidelines, but they are the convention.

If you try to get the Process.ExitCode before the process has exited, the attempt throws an exception. Examine the Process.HasExited property first to verify whether the associated process has terminated.

You can use the System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or the Process.Kill method to cause an associated process to exit.

There are two ways of being notified when the associated process exits: synchronously and asynchronously. Synchronous notification relies on calling the Process.WaitForExit method to pause the processing of your application until the associated component exits. Asynchronous notification relies on the Process.Exited event. In either case, Process.EnableRaisingEvents must be set to true for the Process component to receive notification that the process has exited.

See also:
Process.HasExited | System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) | Process.Kill | Process.WaitForExit | Process.EnableRaisingEvents

Return to top


Property: ExitTime (read-only)
Summary
Gets the time that the associated process exited.
C# Syntax:
public DateTime ExitTime {get;}
Exceptions
Exception Type Condition
PlatformNotSupportedException You are accessing this member using Windows 98.
Remarks
If the process has not terminated, attempting to retrieve the Process.ExitTime property throws an exception. Use Process.HasExited before getting the Process.ExitTime property to determine whether the associated process has terminated.
See also:
Process.Handle | Process.ExitCode

Return to top


Property: Handle (read-only)
Summary
Returns the associated process's native handle.
C# Syntax:
public IntPtr Handle {get;}
Exceptions
Exception Type Condition
InvalidOperationException The process has not been started. The Process.Handle property cannot be read because there is no process associated with this Process instance.

-or-

The Process instance has been attached to a running process but you do not have the necessary permissions to get a handle with full access rights.

Remarks
An application can obtain a handle to a process that can be used as a parameter to many process-information and control functions. This process handle is private to an application--in other words, process handles cannot be shared. A process also has a process Process.Id which, unlike the Process.Handle, is unique and, therefore, valid throughout the system.

Only processes started through a call to Process.Start set the Process.Handle property of the corresponding Process instances.

See also:
Process.Id | Process.ExitCode | Process.ExitTime | System.Diagnostics.Process.HandleCount (not supported on the shared source CLI) | Process.Start | Process.Refresh

Return to top


Property: HasExited (read-only)
Summary
Gets a value indicating whether the associated process has been terminated.
C# Syntax:
public bool HasExited {get;}
Exceptions
Exception Type Condition
InvalidOperationException There is no process associated with the object.
Win32Exception The exit code for the process could not be retrieved.
Remarks
A value of true for Process.HasExited indicates that the associated process has terminated, either normally or abnormally. You can request or force the associated process to exit by calling System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or Process.Kill. When the process has exited, the operating system releases the process memory, but retains administrative information about the process, such as the handle, exit code, and exit time. To get this information, you can use the Process.ExitCode and Process.ExitTime properties. These properties are populated automatically for processes that were started by this component. The administrative information is released when all the Process components that are associated with the system process are destroyed and hold no more handles to the exited process.

A process can terminate independently of your code. If you started the process using this component, the system updates the value of Process.HasExited automatically, even if the associated process exits independently.

See also:
Process.ExitCode | Process.ExitTime | Process.WaitForExit | Process.EnableRaisingEvents | Process.OnExited

Return to top


Property: Id (read-only)
Summary
Gets the unique identifier for the associated process.
C# Syntax:
public int Id {get;}
Exceptions
Exception Type Condition
InvalidOperationException The process's Process.Id property has not been set.

-or-

There is no process associated with this Process object.

Remarks
The process Process.Id does not exist if the associated process is not running. Therefore, you should either ensure that the process is running before attempting to retrieve the Process.Id property or handle the exception that will be thrown if the process has not been started. Until the process terminates, the process identifier uniquely identifies the process throughout the system.

You can connect a process that is running on a local or remote computer to a new Process instance by passing the process identifier to the System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) method. System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) is a static method that creates a new component and sets the Process.Id property for the new Process instance automatically.

Process identifiers can be reused by the system. The Process.Id property value is unique only while the associated process is running. After the process has terminated, the system can reuse the Process.Id property value for an unrelated process.

Because the identifier is unique on the system, you can pass it to other threads as an alternative to passing a Process instance. This action can save system resources yet guarantee that the process is correctly identified.

See also:
Process.Handle | System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI)

Return to top


Property: Site (read-write)
Inherited
See base class member description: System.ComponentModel.Component.Site

Summary
Gets or sets the ISite of the Component.
C# Syntax:
public virtual ISite Site {get; set;}
Implements:
IComponent.Site
Remarks
A Component will have an ISite if it has been added to an IContainer and the IContainer assigns an ISite to it. The IContainer is responsible to assign the ISite to the Component. Changing the value of the component's ISite does not necessarily change the name of the site the Component is assigned to. It is strongly suggested that the setting of the Component.Site property only be done by an IContainer.

The property value is null if the Component is removed from its IContainer. Assigning null to this property does not necessarily remove the Component from the IContainer.

A Component might or might not have a name. If a Component is given a name, the name must be unique among other Component objects within its IContainer. The ISite stores the name of the Component; therefore, you can only name a Component if it has an ISite associated with it.

See also:
IContainer | Container | ISite

Return to top


Property: StandardError (read-only)
Summary
Gets a StreamReader through which to read error output from the application.
C# Syntax:
public StreamReader StandardError {get;}
Exceptions
Exception Type Condition
InvalidOperationException The Process.StandardError value has not been defined. The Process.StartInfo property's ProcessStartInfo.RedirectStandardError may be false.
Remarks
In order to use the Process.StandardError property, you must have specified true for the Process.StartInfo property's ProcessStartInfo.RedirectStandardError property. Otherwise, reading the Process.StandardError property throws an exception.

Note ProcessStartInfo.UseShellExecute on the Process.StartInfo property must be false if you want to set Process.StandardError to true.

The Process component communicates with a child process via a pipe. If a child process writes enough data to the pipe to fill the buffer, the child will block until the parent reads the data from the pipe. This can cause deadlock if your application is reading all output to standard error and standard output, for example, using the following C# code.

              Process p = new Process("...", "...");
              p.StartInfo.UseShellExecute = false;
              p.StartInfo.RedirectStandardOutput = true;
              p.Start();
              p.WaitForExit();
              string output = p.StandardOutput.ReadToEnd();
            

In this instance, both the parent and the child processes would be blocked, as the filled pipe prevents the child process from completing, while the parent process is waiting indefinitely for the child process to exit.

This problem can be solved by moving the ReadToEnd() before the WaitForExit() , as follows.

              Process p = new Process("...", "...");
              p.StartInfo.UseShellExecute = false;
              p.StartInfo.RedirectStandardOutput = true;
              p.Start();
              string output = p.StandardOutput.ReadToEnd();
              p.WaitForExit();
            

A similar problem arises if you redirect both standard output and standard error and then try to read both, for example using the following C# code.

              string output = p.StandardOutput.ReadToEnd();
              string error = p.StandardError.ReadToEnd();
              p.WaitForExit();
            

In this case, if the child process writes any text to standard error it will block the process, because the parent process cannot read from standard error until it has finished reading from standard output. However, the parent process will not read from standard output until the process ends. A recommended solution to this situation is to create two threads so that your application can read the output of each stream on a separate thread.

See also:
Process.StandardInput | Process.StandardOutput | ProcessStartInfo.RedirectStandardError

Return to top


Property: StandardInput (read-only)
Summary
Gets a StreamWriter through which the application can write input to the process.
C# Syntax:
public StreamWriter StandardInput {get;}
Exceptions
Exception Type Condition
InvalidOperationException The Process.StandardInput value has not been defined. The Process.StartInfo property's ProcessStartInfo.RedirectStandardInput may be false or you may not have defined a valid StreamWriter to read from.
Remarks
In order to use input from any source other than standard input, you must have specified true for the Process.StartInfo property's ProcessStartInfo.RedirectStandardInput property. Otherwise, reading the Process.StandardInput property throws an exception.

Note ProcessStartInfo.UseShellExecute on the Process.StartInfo property must be false if you want to set Process.StandardInput to true.
See also:
Process.StandardOutput | Process.StandardError | ProcessStartInfo.RedirectStandardInput

Return to top


Property: StandardOutput (read-only)
Summary
Gets a StreamReader through which the application can read output from the process.
C# Syntax:
public StreamReader StandardOutput {get;}
Exceptions
Exception Type Condition
InvalidOperationException The Process.StandardOutput value has not been defined. The Process.StartInfo property's ProcessStartInfo.RedirectStandardOutput may be false or you may not have defined a valid StreamReader to write to.
Remarks
In order to write output to any source other than standard output, this process component must be associated with a process you have started (rather than a started process you have just attached to), and you must have specified true for the Process.StartInfo property's ProcessStartInfo.RedirectStandardOutput property. Otherwise, reading the Process.StandardOutput property throws an exception.

Note ProcessStartInfo.UseShellExecute on the Process.StartInfo property must be false if you want to set Process.StandardOutput to true.

The Process component communicates with a child process via a pipe. If a child process writes enough data to the pipe to fill the buffer, the child will block until the parent reads the data from the pipe. This can cause deadlock if your application is reading all output to standard error and standard output, for example, using the following C# code.

              Process p = new Process("...", "...");
              p.StartInfo.UseShellExecute = false;
              p.StartInfo.RedirectStandardOutput = true;
              p.Start();
              p.WaitForExit();
              string output = p.StandardOutput.ReadToEnd();
            

In this instance, both the parent and the child processes would be blocked, as the filled pipe prevents the child process from completing, while the parent process is waiting indefinitely for the child process to exit.

This problem can be solved by moving the ReadToEnd() before the WaitForExit() , as follows.

              Process p = new Process("...", "...");
              p.StartInfo.UseShellExecute = false;
              p.StartInfo.RedirectStandardOutput = true;
              p.Start();
              string output = p.StandardOutput.ReadToEnd();
              p.WaitForExit();
            

A similar problem arises if you redirect both standard output and standard error and then try to read both, for example using the following C# code.

              string output = p.StandardOutput.ReadToEnd();
              string error = p.StandardError.ReadToEnd();
              p.WaitForExit();
            

In this case, if the child process writes any text to standard error it will block the process, because the parent process cannot read from standard error until it has finished reading from standard output. However, the parent process will not read from standard output until the process ends. A recommended solution to this situation is to create two threads so that your application can read the output of each stream on a separate thread.

See also:
Process.StandardInput | Process.StandardError | ProcessStartInfo.RedirectStandardOutput

Return to top


Property: StartInfo (read-write)
Summary
Gets or sets the properties to pass to the Process.Start method of the Process.
C# Syntax:
public ProcessStartInfo StartInfo {get; set;}
Exceptions
Exception Type Condition
ArgumentException The value that specifies the Process.StartInfo is null.
Remarks
Process.StartInfo represents the set of parameters to use to start a process. When Process.Start is called, the Process.StartInfo is used to specify the process to start.

The only necessary Process.StartInfo member to set is the ProcessStartInfo.FileName property. Starting a process by specifying the ProcessStartInfo.FileName property is similar to typing the information in the Run dialog box of the Windows Start menu. Therefore, the ProcessStartInfo.FileName property does not need to represent an executable file. It can be of any file type for which the extension has been associated with an application installed on the system. For example the ProcessStartInfo.FileName can have a .txt extension if you have associated text files with an editor, such as Notepad, or it can have a .doc if you have associated .doc files with a word processing tool, such as Microsoft Word. Similarly, in the same way that the Run dialog box can accept an executable file name with or without the .exe extension, the .exe extension is optional in the ProcessStartInfo.FileName member. For example, you can set the ProcessStartInfo.FileName property to either "Notepad.exe" or "Notepad".

If the file name involves a non-executable file, such as a .doc file, you can include a verb specifying what action to take on the file. For example, you could set the System.Diagnostics.ProcessStartInfo.Verb (not supported on the shared source CLI) to "Print" for a file ending in the .doc extension. The file name specified in the ProcessStartInfo.FileName property does not need to have an extension if you manually enter a value for the System.Diagnostics.ProcessStartInfo.Verb (not supported on the shared source CLI) property. However, if you use the System.Diagnostics.ProcessStartInfo.Verbs (not supported on the shared source CLI) property to determine what verbs are available, you must include the file extension.

When the process is started, the file name is the file that populates the (read-only) System.Diagnostics.Process.MainModule (not supported on the shared source CLI) property. If you want to retrieve the executable file that is associated with the process after the process has started, use the System.Diagnostics.Process.MainModule (not supported on the shared source CLI) property. If you want to set the executable file of a Process instance for which an associated process has not been started, use the Process.StartInfo property's ProcessStartInfo.FileName member. Because the members of the Process.StartInfo property are arguments that are passed to the Process.Start method of a process, changing the ProcessStartInfo.FileName property after the associated process has started will not reset the System.Diagnostics.Process.MainModule (not supported on the shared source CLI) property. These properties are used only to initialize the associated process.

See also:
Process.Start | ProcessStartInfo.FileName

Return to top


Property: SynchronizingObject (read-write)
Summary
Gets or sets the object used to marshal the event handler calls that are issued as a result of a process exit event.
C# Syntax:
public ISynchronizeInvoke SynchronizingObject {get; set;}
Remarks
When System.Diagnostics.EventLog.SynchronizingObject (not supported on the shared source CLI) is null, methods handling the Process.Exited event are called on a thread from the system thread pool. For more information on system thread pools, see ThreadPool.

When the Process.Exited event is handled by a visual Windows Forms component, such as a Button, accessing the component through the system thread pool might not work, or may result in an exception. Avoid this by setting Process.SynchronizingObject to a Windows Forms component, which causes the methods handling the Process.Exited event to be called on the same thread on which the component was created.

If the Process is used inside Visual Studio .NET in a Windows Forms designer, Process.SynchronizingObject is automatically set to the control containing the Process. For example, if you place a Process on a designer for Form1 (which inherits from Form) the Process.SynchronizingObject property of Process is set to the instance of Form1.

Typically, this property is set when the component is placed inside a control or form, because those components are bound to a specific thread.

Example
      private MyButton button1;
      private void button1_Click(object sender, System.EventArgs e)
      {
         Process myProcess = new Process();
         ProcessStartInfo myProcessStartInfo= new ProcessStartInfo("mspaint");
         myProcess.StartInfo = myProcessStartInfo;
         myProcess.Start();
         myProcess.Exited += new EventHandler(button1.MyProcessExited);
         // Set 'EnableRaisingEvents' to true, to raise 'Exited' event when process is terminated.
         myProcess.EnableRaisingEvents = true;
         // Set method handling the exited event to be called  ;
         // on the same thread on which MyButton was created.
         myProcess.SynchronizingObject = button1;
         MessageBox.Show("Waiting for the process 'mspaint' to exit....");
         myProcess.WaitForExit();
         myProcess.Close();
      }
   }

   public class MyButton:Button
   {
      public void MyProcessExited(Object source, EventArgs e)
      {
         MessageBox.Show("The process has exited.");
      }
   }

    

Return to top


Method: Close()
Summary
Frees all the resources that are associated with this component.
C# Syntax:
public void Close();

Return to top


Method: CreateObjRef(
   Type requestedType
)
Inherited
See base class member description: System.MarshalByRefObject.CreateObjRef

Summary
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
C# Syntax:
public virtual ObjRef CreateObjRef(
   Type requestedType
);
Parameters:

requestedType

The Type of the object that the new ObjRef will reference.

Return Value:
Information required to generate a proxy.
Exceptions
Exception Type Condition
RemotingException This instance is not a valid remoting object.

Return to top


Overloaded Method: Dispose()
Inherited
See base class member description: System.ComponentModel.Component.Dispose

Summary
Releases all resources used by the Component.
C# Syntax:
public void Dispose();
Implements:
IDisposable.Dispose
Remarks
Calling Component.Dispose allows the resources used by the Component to be reallocated for other purposes. For more information about Component.Dispose, see the conceptual topic at MSDN: cleaningupunmanagedresources.
See also:
IContainer | Container

Return to top


Overloaded Method: Dispose(
   bool disposing
)
Summary
Supports the Shared Source CLI infrastructure and is not intended to be used directly from your code
This type supports the Shared Source CLI infrastructure and is not intended to be used directly from your code.
C# Syntax:
protected override void Dispose(
   bool disposing
);
Parameters:

disposing

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~Process();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetCurrentProcess()
Summary
Gets a new Process component and associates it with the currently active process.
C# Syntax:
public static Process GetCurrentProcess();
Return Value:
A new Process component associated with the process resource that is running the calling application.
Remarks
Use this method to create a new Process instance and associate it with the process resource on the local computer.

Like the similar System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) , System.Diagnostics.Process.GetProcessesByName (not supported on the shared source CLI) , and System.Diagnostics.Process.GetProcesses (not supported on the shared source CLI) methods, Process.GetCurrentProcess associates an existing resource with a new Process component.

See also:
System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) | System.Diagnostics.Process.GetProcessesByName (not supported on the shared source CLI) | System.Diagnostics.Process.GetProcesses (not supported on the shared source CLI)

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.GetLifetimeService

Summary
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
C# Syntax:
public object GetLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance.
Remarks
For more information about lifetime services, see the LifetimeServices class.

Return to top


Method: GetService(
   Type service
)
Inherited
See base class member description: System.ComponentModel.Component.GetService

Summary
Returns an object that represents a service provided by the Component or by its Container.
C# Syntax:
protected virtual object GetService(
   Type service
);
Parameters:

service

A service provided by the Component.

Return Value:
An Object that represents a service provided by the Component.

This value is null if the Component does not provide the specified service.

Remarks
This method can be overridden by a derived class.
See also:
IContainer | Container | ISite | IServiceProvider

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: InitializeLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.InitializeLifetimeService

Summary
Obtains a lifetime service object to control the lifetime policy for this instance.
C# Syntax:
public virtual object InitializeLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the LifetimeServices.LeaseManagerPollTime property.
Remarks
For more information about lifetime services, see the LifetimeServices class.
Example
The following code example demonstrates creating a lease.
 public class MyClass : MarshalByRefObject
 {
   public override Object InitializeLifetimeService()
   {
     ILease lease = (ILease)base.InitializeLifetimeService();
     if (lease.CurrentState == LeaseState.Initial)
     {
          lease.InitialLeaseTime = TimeSpan.FromMinutes(1);
          lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
           lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
     }
       return lease;
   }
 }

    

Return to top


Method: Kill()
Summary
Immediately stops the associated process.
C# Syntax:
public void Kill();
Exceptions
Exception Type Condition
Win32Exception The associated process could not be terminated.
SystemException No process Process.Id has been set, and a Process.Handle from which the Process.Id property can be determined does not exist.

-or-

There is no process associated with this Process object.

-or-

You are attempting to call Process.Kill for a process that is running on a remote computer. The method is available only for processes running on the local computer.

InvalidOperationException The process has already exited.
Remarks
Process.Kill forces a termination of the process, while System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) only requests a termination. When a process with a graphical interface is executing, its message loop is in a wait state. The message loop executes every time a Windows message is sent to the process by the operating system. Calling System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) revokes all the running message loops for all threads and closes all windows. The request to exit the process by calling System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) does not force the application to quit. The application can ask for user verification before quitting, or it can refuse to quit if it is running a macro. To force the application to quit, use the Process.Kill method. The behavior of System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) is identical to that of a user closing an application's main window using the system menu. Therefore, the request to exit the process by closing the main window does not force the application to quit immediately.

Data edited by the process or resources allocated to the process can be lost if you call Process.Kill. Process.Kill causes an abnormal process termination and should be used only when necessary. System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) enables an orderly termination of the process and closes all windows, so it is preferable for applications with an interface. If System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) fails, you can use Process.Kill to terminate the process. Process.Kill is the only way to terminate processes that do not have graphical interfaces.

You can call Process.Kill and System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) only for processes that are running on the local computer. You cannot cause processes on remote computers to exit. You can only view information for processes running on remote computers.

See also:
System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) | Process.Start

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: OnExited()
Summary
Raises the Process.Exited event.
C# Syntax:
protected void OnExited();
Remarks
Process.OnExited is the API method that raises the Process.Exited event. Calling Process.OnExited causes the Process.Exited event to occur and is the only way to raise the event using the Process component. Process.OnExited is primarily used when deriving classes from the component.

As an alternative to Process.OnExited, you can write your own event handler. You create your own event handler delegate and your own event-handling method.



Note If you are using the Visual Studio environment, an event handler delegate (AddOnExited) and an event-handling method (Process1_Exited) are created for you when you drag a Process component onto a form and double-click the icon. The code you create to run when the Process.Exited event occurs is entered into the Process1_Exited procedure. You do not need to create the Process.OnExited member, because it is implemented for you.

Raising an event invokes the event handler through a delegate. For an overview, see the conceptual topic at MSDN: providingeventfunctionality.



Notes to inheritors: When overriding Process.OnExited in a derived class, be sure to call the base class's Process.OnExited method.
See also:
Process.Exited

Return to top


Method: Refresh()
Summary
Discards any information about the associated process that has been cached inside the process component.
C# Syntax:
public void Refresh();
Remarks
After Process.Refresh is called, the first request for information about each property causes the process component to obtain a new value from the associated process.

When a Process component is associated with a process resource, the property values of the Process are immediately populated according to the status of the associated process. If the information about the associated process subsequently changes, those changes are not reflected in the Process component's cached values. The Process component is a snapshot of the process resource at the time they are associated. To view the current values for the associated process, call the Process.Refresh method.

Return to top


Overloaded Method: Start()
Summary
Starts (or reuses) the process resource that is specified by the Process.StartInfo property of this Process component and associates it with the component.
C# Syntax:
public bool Start();
Return Value:
true if a process resource is started; false if no new process resource is started (for example, if an existing process is reused).
Exceptions
Exception Type Condition
InvalidOperationException No file name was specified in the Process component's Process.StartInfo.

-or-

The ProcessStartInfo.UseShellExecute member of the Process.StartInfo property is true while ProcessStartInfo.RedirectStandardInput, ProcessStartInfo.RedirectStandardOutput, or ProcessStartInfo.RedirectStandardError is true.

Win32Exception There was an error in opening the associated file.
ObjectDisposedException The process object has already been disposed.
Remarks
Use this overload to start a process resource and associate it with the current Process component. The return value true indicates that a new process resource was started. If the process resource specified by the ProcessStartInfo.FileName member of the Process.StartInfo property is already running on the computer, no additional process resource is started. Instead, the running process resource is reused and false is returned.

Note If you are using Visual Studio, this overload of the Process.Start method is the one that you insert into your code after you drag a Process component onto the designer. Use the Properties window to expand the StartInfo category and write the appropriate value into the FileName property. Your changes will appear in the form's InitializeComponent procedure.

This overload of Process.Start is not a static method. You must call it for an instance of the Process class. Before calling Process.Start, you must first specify Process.StartInfo property information for this Process instance, because that information is used to determine the process resource to start.

The other overloads of the Process.Start method are static members. You do not need to create an instance of the Process component before you call those overloads of the method. Instead, you can call Process.Start for the Process class itself, and a new Process component is created if the process was started. Or, null is returned if a process was reused. The process resource is automatically associated with the new Process component that is returned by the Process.Start method.

The Process.StartInfo members can be used to duplicate the functionality of the Run dialog box of the Windows Start menu. Anything that can be typed into a command line can be started by setting the appropriate values in the Process.StartInfo property. The only Process.StartInfo property that must be set is the ProcessStartInfo.FileName property. The ProcessStartInfo.FileName property does not have to be an executable file. It can be of any file type for which the extension has been associated with an application that is installed on the system. For example, the ProcessStartInfo.FileName property can have a .txt extension if you have associated text files with an editor, such as Notepad, or it can have a .doc extension if you have associated .doc files with a word processing tool, such as Microsoft Word.

In the command line, you can specify actions to take for certain types of files. For example, you can print documents or edit text files. Specify these actions using the System.Diagnostics.ProcessStartInfo.Verb (not supported on the shared source CLI) member of the Process.StartInfo property. For other types of files, you can specify command line arguments when you start the file from the Run dialog box. For example, you can pass a URL as an argument if you specify your browser as the ProcessStartInfo.FileName. These arguments can be specified in the Process.StartInfo property's ProcessStartInfo.Arguments member.

Whenever you use Process.Start to start a process, you might need to close it or you risk losing system resources. Close processes using System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or Process.Kill.

A note about apartment states in managed threads is necessary here. When ProcessStartInfo.UseShellExecute is true on the process component's Process.StartInfo property, make sure you have set a threading model on your application by setting the attribute [STAThread] on the main() method. Otherwise, a managed thread can be in an unknown state or put in the MTA state, the latter of which conflicts with ProcessStartInfo.UseShellExecute being true. Some methods require that the apartment state not be unknown. If the state is not explicitly set, when the application encounters such a method, it defaults to MTA, and once set, the apartment state cannot be changed. However, MTA causes an exception to be thrown when the operating system shell is managing the thread.

Example
The following example demonstrates how to start one of four processes (Word, Excel, Internet Explorer, or Notepad), depending on information passed to the procedure that describes a document. The example assigns information to an existing process object and starts the procedure.

StartProcess takes two parameters. The first parameter is the name of a document, meaning any file that has an open action associated with it (for example, MyDoc.doc or MyFile.txt). The second parameter is the document's extension (.doc, .txt, .htm., or .xls). Using the extension, the StartProcess procedure associates an application with the Process component's Process.StartInfo property. Then, the document itself is passed as an argument with which the application is opened. In the case of Excel or Word, the document is opened in order to be printed. In the case of Notepad or Internet Explorer, the document is only loaded into the application's window.

The file name and arguments are the same as you would type into the Run dialog box of the Windows Start menu.

See also:
Process.StartInfo | ProcessStartInfo.FileName | ProcessStartInfo | System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) | Process.Kill

Return to top


Overloaded Method: Start(
   ProcessStartInfo startInfo
)
Summary
Starts the process resource that is specified by the parameter containing process start information (for example, the file name of the process to start) and associates the resource with a new Process component.
C# Syntax:
public static Process Start(Process Start(
   ProcessStartInfo startInfo
);
Parameters:

startInfo

The ProcessStartInfo that contains the information that is used to start the process, including the file name and any command line arguments.

Return Value:
A new Process component that is associated with the process resource, or null if no process resource is started (for example, if an existing process is reused).
Exceptions
Exception Type Condition
InvalidOperationException No file name was specified in the startInfo parameter's ProcessStartInfo.FileName property.

-or-

The ProcessStartInfo.UseShellExecute member of the startInfo parameter is true while ProcessStartInfo.RedirectStandardInput, ProcessStartInfo.RedirectStandardOutput, or ProcessStartInfo.RedirectStandardError is true.

ArgumentException The startInfo parameter is null.
Win32Exception There was an error in opening the associated file.
ObjectDisposedException The process object has already been disposed.
Remarks
Use this overload to start a process resource by specifying a ProcessStartInfo instance. The overload associates the resource with a new Process component. If the process is already running, no additional process resource is started. Instead, the existing process resource is reused and no new Process component is created. In such a case, instead of returning a new Process component, Process.Start returns null to the calling procedure.

This overload lets you start a process without first creating a new Process instance. Using this overload with a ProcessStartInfo parameter is an alternative to the explicit steps of creating a new Process instance, setting its Process.StartInfo properties, and calling Process.Start for the Process instance.

Using a ProcessStartInfo instance as the parameter lets you call Process.Start with the most control over what is passed into the call to start the process. If you need to pass only a file name or a file name and arguments, it is not necessary to create a new ProcessStartInfo instance, although that is an option. The only Process.StartInfo property that must be set is the ProcessStartInfo.FileName property. The ProcessStartInfo.FileName property does not need to represent an executable file. It can be of any file type for which the extension has been associated with an application that is installed on the system. For example, the ProcessStartInfo.FileName property can have a .txt extension if you have associated text files with an editor, such as Notepad, or it can have a .doc extension if you have associated .doc files with a word processing tool, such as Microsoft Word.

Unlike the other overloads, the overload of Process.Start that has no parameters is not a static member. Use that overload when you have already created a Process instance, specified start information (including the file name), and want to start a process resource and associate it with the existing Process instance. Use one of the static overloads when you want to create a new Process component rather than start a process for an existing component. Both this overload and the overload that has no parameters allow you to specify the start information for the process resource by using a ProcessStartInfo instance.

Whenever you use Process.Start to start a process, you might need to close it or you risk losing system resources. Close processes using System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or Process.Kill.

A note about apartment states in managed threads is necessary here. When ProcessStartInfo.UseShellExecute is true on the startInfo parameter, make sure you have set a threading model on your application by setting the attribute [STAThread] on the main() method. Otherwise, a managed thread can be in an unknown state or put in the MTA state, the latter of which conflicts with ProcessStartInfo.UseShellExecute being true. Some methods require that the apartment state not be unknown. If the state is not explicitly set, when the application encounters such a method, it defaults to MTA, and once set, the apartment state cannot be changed. However, MTA causes an exception to be thrown when the operating system shell is managing the thread.

See also:
Process.StartInfo | ProcessStartInfo.FileName | ProcessStartInfo | System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) | Process.Kill

Return to top


Overloaded Method: Start(
   string fileName
)
Summary
Starts a process resource by specifying the name of a document or application file and associates the resource with a new Process component.
C# Syntax:
public static Process Start(
   string fileName
);
Parameters:

fileName

The name of a document or application file to run in the process.

Return Value:
A new Process component that is associated with the process resource, or null, if no process resource is started (for example, if an existing process is reused).
Exceptions
Exception Type Condition
ArgumentException The fileName parameter is null.
Win32Exception There was an error in opening the associated file.
ObjectDisposedException The process object has already been disposed.
Remarks
Use this overload to start a process resource by specifying its file name. The overload associates the resource with a new Process component. If the process is already running, no additional process resource is started. Instead, the existing process resource is reused and no new Process component is created. In such a case, instead of returning a new Process component, Process.Start returns null to the calling procedure.

This overload lets you start a process without first creating a new Process instance. The overload is an alternative to the explicit steps of creating a new Process instance, setting the ProcessStartInfo.FileName member of the Process.StartInfo property, and calling Process.Start for the Process instance.

Starting a process by specifying its file name is similar to typing the information in the Run dialog box of the Windows Start menu. Therefore, the file name does not need to represent an executable file. It can be of any file type for which the extension has been associated with an application installed on the system. For example the file name can have a .txt extenstion if you have associated text files with an editor, such as Notepad, or it can have a .doc if you have associated .doc files with a word processing tool, such as Microsoft Word. Similarly, in the same way that the Run dialog box can accept an executable file name with or without the .exe extension, the .exe extension is optional in the fileName parameter. For example, you can set the fileName parameter to either "Notepad.exe" or "Notepad".

Unlike the other overloads, the overload of Process.Start that has no parameters is not a static member. Use that overload when you have already created a Process instance, specified start information (including the file name), and want to start a process resource and associate it with the existing Process instance. Use one of the static overloads when you want to create a new Process component rather than start a process for an existing component. Both this overload and the overload that has no parameters allow you to specify the file name of the process resource to start.

Whenever you use Process.Start to start a process, you might need to close it or you risk losing system resources. Close processes using System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or Process.Kill.

A note about apartment states in managed threads is necessary here. When ProcessStartInfo.UseShellExecute is true on the process component's Process.StartInfo property, make sure you have set a threading model on your application by setting the attribute [STAThread] on the main() method. Otherwise, a managed thread can be in an unknown state or put in the MTA state, the latter of which conflicts with ProcessStartInfo.UseShellExecute being true. Some methods require that the apartment state not be unknown. If the state is not explicitly set, when the application encounters such a method, it defaults to MTA, and once set, the apartment state cannot be changed. However, MTA causes an exception to be thrown when the operating system shell is managing the thread.

Example
The following example demonstrates how to open Notepad by passing the name of the application to the Process.Start method. Because Notepad could receive a close request before the window has opened and initialized, the example causes the application to wait until Notepad is in its message loop and in an idle state before receiving input. The example results in the opening of a blank Notepad window.
See also:
ProcessStartInfo.FileName | Process.StartInfo | System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) | Process.Kill

Return to top


Overloaded Method: Start(
   string fileName,
   string arguments
)
Summary
Starts a process resource by specifying the name of an application and a set of command line arguments, and associates the resource with a new Process component.
C# Syntax:
public static Process Start(
   string fileName,
   string arguments
);
Parameters:

fileName

The name of an application file to run in the process.

arguments

Command line arguments to pass when starting the process.

Return Value:
A new Process component that is associated with the process, or null, if no process resource is started (for example, if an existing process is reused).
Exceptions
Exception Type Condition
ArgumentException The fileName or arguments parameter is null.
Win32Exception There was an error in opening the associated file.
ObjectDisposedException The process object has already been disposed.
Remarks
Use this overload to start a process resource by specifying its file name and command line arguments. The overload associates the resource with a new Process component. If the process is already running, no additional process is started. Instead, the existing process resource is reused and no new Process component is created. In such a case, instead of returning a new Process component, Process.Start returns null to the calling procedure.

This overload lets you start a process without first creating a new Process instance. The overload is an alternative to the explicit steps of creating a new Process instance, setting the ProcessStartInfo.FileName and ProcessStartInfo.Arguments members of the Process.StartInfo property, and calling Process.Start for the Process instance.

Starting a process by specifying its file name and arguments is similar to typing the file name and command line arguments in the Run dialog box of the Windows Start menu. Therefore, the file name does not need to represent an executable file. It can be of any file type for which the extension has been associated with an application installed on the system. For example the file name can have a .txt extenstion if you have associated text files with an editor, such as Notepad, or it can have a .doc if you have associated .doc files with a word processing tool, such as Microsoft Word. Similarly, in the same way that the Run dialog box can accept an executable file name with or without the .exe extension, the .exe extension is optional in the fileName parameter. For example, you can set the fileName parameter to either "Notepad.exe" or "Notepad". If the fileName parameter represents an executable file, the arguments parameter may represent a file to act upon, such as the text file in Notepad.exe myfile.txt .

Unlike the other overloads, the overload of Process.Start that has no parameters is not a static member. Use that overload when you have already created a Process instance, specified start information (including the file name), and want to start a process resource and associate it with the existing Process instance. Use one of the static overloads when you want to create a new Process component rather than start a process for an existing component. Both this overload and the overload that has no parameters allow you to specify the file name of the process resource to start and command line arguments to pass.

Whenever you use Process.Start to start a process, you might need to close it or you risk losing system resources. Close processes using System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or Process.Kill.

A note about apartment states in managed threads is necessary here. When ProcessStartInfo.UseShellExecute is true on the process component's Process.StartInfo property, make sure you have set a threading model on your application by setting the attribute [STAThread] on the main() method. Otherwise, a managed thread can be in an unknown state or put in the MTA state, the latter of which conflicts with ProcessStartInfo.UseShellExecute being true. Some methods require that the apartment state not be unknown. If the state is not explicitly set, when the application encounters such a method, it defaults to MTA, and once set, the apartment state cannot be changed. However, MTA causes an exception to be thrown when the operating system shell is managing the thread.

Example
The following example demonstrates how to start Internet Explorer as a process from within your application. The example passes the URL http://www.microsoft.com as an argument to the Process.Start method. The file name and arguments pair is the same as you would type directly into the Run dialog box (which is accessed from the Windows Start menu). The example results in the opening of the browser window.
See also:
ProcessStartInfo.FileName | Process.StartInfo | ProcessStartInfo | System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) | Process.Kill

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: WaitForExit()
Summary
Instructs the Process component to wait indefinitely for the associated process to exit.
C# Syntax:
public void WaitForExit();
Exceptions
Exception Type Condition
Win32Exception The wait setting could not be accessed.
SystemException No process Process.Id has been set, and a Process.Handle from which the Process.Id property can be determined does not exist.

-or-

There is no process associated with this Process object.

-or-

You are attempting to call Process.WaitForExit for a process running on a remote computer. The method is available only for processes that are running on the local computer.

Remarks
Process.WaitForExit is used to make the current thread wait until the associated process terminates.

This overload of Process.WaitForExit instructs the Process component to wait an infinite amount of time for the process to exit. This can cause an application to stop responding. For example, if you call System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) for a process that has a user interface, the request to the operating system to terminate the associated process might not be handled if the process is written to never enter its message loop.

When an associated process exits (is shut down by the operation system through a normal or abnormal termination), the system stores administrative information about the process and returns to the component that had called Process.WaitForExit. The Process component can then access the information, which includes the Process.ExitTime, by using the Process.Handle to the exited process.

Because the associated process has exited, the Process.Handle property of the component no longer points to an existing process resource. Instead, the handle can be used only to access the operating system's information about the process resource. The system is aware of handles to exited processes that have not been released by Process components, so it keeps the Process.ExitTime and Process.Handle information in memory until the Process component specifically frees the resources. For this reason, any time you call Process.Start for a Process instance, call Process.Close when the associated process has terminated and you no longer need any administrative information about it. Process.Close frees the memory allocated to the exited process.

See also:
System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) | Process.Kill | Process.Handle | Process.ExitTime | Process.EnableRaisingEvents | Process.HasExited | Process.Exited

Return to top


Overloaded Method: WaitForExit(
   int milliseconds
)
Summary
Instructs the Process component to wait the specified number of milliseconds for the associated process to exit.
C# Syntax:
public bool WaitForExit(
   int milliseconds
);
Parameters:

milliseconds

The amount of time, in milliseconds, to wait for the associated process to exit. The maximum is the largest possible value of a 32-bit integer, which represents infinity to the operating system.

Return Value:
true if the associated process has exited; otherwise, false.
Exceptions
Exception Type Condition
Win32Exception The wait setting could not be accessed.
SystemException No process Process.Id has been set, and a Process.Handle from which the Process.Id property can be determined does not exist.

-or-

There is no process associated with this Process object.

-or-

You are attempting to call Process.WaitForExit for a process running on a remote computer. The method is only available for processes that are running on the local computer.

Remarks
Process.WaitForExit is used to make the current thread wait until the associated process terminates.

This overload of Process.WaitForExit instructs the Process component to wait a finite amount of time for the process to exit. If the associated process does not exit by the end of the interval because the request to terminate is denied, false is returned to the calling procedure. You can specify a negative number for milliseconds, but it is treated by Process.WaitForExit as a very large positive number. If you pass zero to the method, it returns true only if the process has already exited.

When an associated process exits (is shut down by the operation system through a normal or abnormal termination), the system stores administrative information about the process and returns to the component that had called Process.WaitForExit. The Process component can then access the information, which includes the Process.ExitTime, by using the Process.Handle to the exited process.

Because the associated process has exited, the Process.Handle property of the component no longer points to an existing process resource. Instead, the handle can be used only to access the operating system's information about the process resource. The system is aware of handles to exited processes that have not been released by Process components, so it keeps the Process.ExitTime and Process.Handle information in memory until the Process component specifically frees the resources. For this reason, any time you call Process.Start for a Process instance, call Process.Close when the associated process has terminated and you no longer need any administrative information about it. Process.Close frees the memory allocated to the exited process.

See also:
System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) | Process.Kill | Process.Handle | Process.ExitTime | Process.EnableRaisingEvents | Process.HasExited | Process.Exited

Return to top


Event: Disposed
Inherited
See base class member description: System.ComponentModel.Component.Disposed

Summary
Adds an event handler to listen to the Component.Disposed event on the component.
C# Syntax:
public event EventHandler Disposed;
Remarks
When you create a Component.Disposed delegate, you identify the method that handles the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about the event handler delegates, see the conceptual topic at MSDN: eventsdelegates.
See also:
EventHandler

Return to top


Event: Exited
Summary
Occurs when a process exits.
C# Syntax:
public event EventHandler Exited;
Remarks
The Process.Exited event indicates that the associated process exited. This occurrence means either that the process terminated (aborted) or successfully closed. When the operating system shuts down a process, any process component that is waiting for an exit is notified. The component can then access the associated process information that is still resident in the operating system memory (such as Process.ExitTime property) by using the handle that it has to the process.

Because the associated process has exited, the Process.Handle property of the component no longer points to an existing process resource. Instead, it can be used only to access the operating system's information about the process resource. The system is aware of handles to exited processes that have not been released by Process components, so it keeps the Process.ExitTime and Process.Handle property information in memory until the Process component specifically frees the resources.



Note Even if you have a handle to an exited process, you cannot call Process.Start again to reconnect to the same process. Calling Process.Start automatically releases the associated process and connects to a process with the same file but an entirely new Process.Handle.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.