Skip to content

Commit

Permalink
make accessing process.StartTime best-effort
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesmanning committed Jul 9, 2018
1 parent c63ae3a commit 7507db4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
29 changes: 18 additions & 11 deletions src/RunProcessAsTask/ProcessEx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,6 @@ namespace RunProcessAsTask
{
public static partial class ProcessEx
{
public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo)
=> RunAsync(processStartInfo, CancellationToken.None);

public static async Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken)
{
return await RunAsync(processStartInfo, new List<string>(), new List<string>(), cancellationToken);
}

public static async Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, List<string> standardOutput, List<string> standardError, CancellationToken cancellationToken)
{
// force some settings in the start info so we can capture the output
Expand Down Expand Up @@ -73,12 +65,27 @@ await standardErrorResults.Task.ConfigureAwait(false)
})) {
cancellationToken.ThrowIfCancellationRequested();

var startTime = DateTime.Now;
if (process.Start() == false)
{
tcs.TrySetException(new InvalidOperationException("Failed to start process"));
processStartTime.SetResult(process.StartTime);
}
else
{
try
{
startTime = process.StartTime;
}
catch (Exception)
{
// best effort to try and get a more accurate start time, but if we fail to access StartTime
// (for instance, process has already existed), we still have a valid value to use.
}
processStartTime.SetResult(startTime);

process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
}

return await tcs.Task.ConfigureAwait(false);
}
Expand Down
7 changes: 7 additions & 0 deletions src/RunProcessAsTask/ProcessEx.overloads.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace RunProcessAsTask
Expand All @@ -15,5 +16,11 @@ public static Task<ProcessResults> RunAsync(string fileName)

public static Task<ProcessResults> RunAsync(string fileName, string arguments)
=> RunAsync(new ProcessStartInfo(fileName, arguments));

public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo)
=> RunAsync(processStartInfo, CancellationToken.None);

public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken) =>
RunAsync(processStartInfo, new List<string>(), new List<string>(), cancellationToken);
}
}

0 comments on commit 7507db4

Please sign in to comment.