Skip to content

[API Proposal]: Process HasStarted property #120605

@alastairlundy

Description

@alastairlundy

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:

    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

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.

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.

namespace System.Diagnostics;

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

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions