dotnet / dotnet/runtime

[API Proposal]: Process ``HasStarted`` property

Open
#120,605 4 comments 2 reactions 1 assignee Claimed by @adamsitnik View on GitHub
api-suggestion area-System.Diagnostics.Process
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Background and motivation

Trying to figure out programatically if a specific Process in .NET has started is difficult/next to impossible right now without having an exception being thrown or avoiding the exception by looking specifically for it with a Try/Catch, or potentially some other convoluted way.

It would be nice to not have to rely on a Try/Catch to spot an Invalid Operation Exception when accessing Process.StartTime to figure out if a Process has started.

Here's the code I use as a workaround right now:
```csharp
internal static bool HasStarted(this Process process)
{
try
{
return process.StartTime.ToUniversalTime() <= DateTime.UtcNow;
}
catch(InvalidOperationException)
{
return false;
}
}
```

The code works because the StartTime property will throw an exception which is caught if the Process hasn't started, and will evaluate to true if it has started. It would be nice to not have to rely on this.

### API Proposal

```csharp
namespace System.Diagnostics;

public class Process : Component, IDisposable
{
public bool HasStarted { get; }
}
```

### API Usage

Here's an example for setting Processor Affinity - The ``ProcessorAffinity`` property requires the Process to be started but not exited in order to be set without an exception being thrown.

```csharp

if(process.HasStarted && !process.HasExited)
{
// Do something that requires the Process to have been started but not yet exited.
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux())
{
if (processorAffinity is not null)
{
process.ProcessorAffinity = processorAffinity;
}
}
}
```

### Alternative Designs

One alternative could be to allow all Process properties to be set before being started but this may be more work than creating a ``HasStarted`` property.

Another alternative could be publicly exposing Process State via the API but this would be less helpful.

e.g.

```csharp
namespace System.Diagnostics;

public class Process : Component, IDisposable
{
public Process.State State { get; }
}
```

### Risks

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.