Skip to content

Avoid throwing in ToString() if the process has already exited #53979

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1361,15 +1361,31 @@ private void StopWatchingForExit()

public override string ToString()
{
if (Associated)
string result = base.ToString();

try
{
string processName = ProcessName;
if (processName.Length != 0)
if (Associated)
{
return $"{base.ToString()} ({processName})";
_processInfo ??= ProcessManager.GetProcessInfo(_processId, _machineName);
if (_processInfo is not null)
{
string processName = _processInfo.ProcessName;
if (processName.Length != 0)
{
result = $"{result} ({processName})";
}
}
}
}
return base.ToString();
catch
{
// Common contract for ToString methods is never throw.
// Handle cases where a process would terminates immediately after our checks
// and/or cause ProcessManager to throw an exception.
}

return result;
}

/// <devdoc>
Expand Down
21 changes: 21 additions & 0 deletions src/libraries/System.Diagnostics.Process/tests/ProcessTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,27 @@ public void TestHasExited()
}
}

[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void TestToString_OnRunningProcess()
{
Process p = CreateDefaultProcess();
var name = p.ProcessName;
Assert.Equal($"System.Diagnostics.Process ({name})", p.ToString());

KillWait(p);
}

[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void TestToString_OnExitedProcess()
{
Process p = CreateDefaultProcess();
KillWait(p);

// Ensure ToString does not throw an exception, but still returns
// a representation of the object.
Assert.Equal("System.Diagnostics.Process", p.ToString());
}

[Fact]
public void HasExited_GetNotStarted_ThrowsInvalidOperationException()
{
Expand Down