Skip to content

Commit

Permalink
Battle hardening ProcessRunner for .NET Core
Browse files Browse the repository at this point in the history
It looks like somewhere along the .NET Core path, the Process object got a bit more throw-ey... especially around the `HasExited` property.

Work done for #196
  • Loading branch information
atruskie committed Mar 11, 2020
1 parent ec4502f commit 671d93f
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions src/Acoustics.Shared/ProcessRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -191,13 +191,41 @@ public void Dispose()
{
if (this.process != null)
{
if (!this.process.HasExited)
bool exited;
try
{
exited = this.process.HasExited;
}
catch (InvalidOperationException ioex)
{
if (Log.IsVerboseEnabled())
{
Log.Verbose("Exception occurred while disposing a process (and was ignored):", ioex);
}

exited = true;
}
catch (Win32Exception wex)
{
// this case no longer occurs in .NET Core 3+

// access denied exception. Either not enough rights, or process already terminating
if (Log.IsVerboseEnabled())
{
Log.Verbose("Exception occurred while disposing a process (and was ignored):", wex);
}

exited = true;
}

if (!exited)
{
this.KillProcess();
}

// https://github.com/QutBioacoustics/audio-analysis/issues/118
// Workaround for: https://bugzilla.xamarin.com/show_bug.cgi?id=43462#c14
// TODO core: remove?
this.process.Dispose();

GC.Collect();
Expand Down Expand Up @@ -254,13 +282,14 @@ private void KillProcess()

while (exceptions.Count < 10)
{
bool added = false;
try
{
// kill?
this.process.Refresh();
if (!this.process.HasExited)
{
this.process.Kill();
this.process.Kill(entireProcessTree: true);
}

// has killed? clean up
Expand All @@ -282,10 +311,26 @@ private void KillProcess()

// has not killed? wait and try again
}
catch (InvalidOperationException ioex)
{
exceptions.Add(ioex);
added = true;
}
catch (Win32Exception wex)
{
// this case no longer occurs in .NET Core 3+

// access denied exception. Either not enough rights, or process already terminating
exceptions.Add(wex);
added = true;
}

// https://developers.redhat.com/blog/2019/10/29/the-net-process-class-on-linux/
// because an exception is no longer thrown in .NET Core 3+ we have to increment this loop
// otherwise we risk an infinite loop.
if (!added)
{
exceptions.Add(null);
}

// Wait a short while, let the process attempt to kill itself
Expand Down

0 comments on commit 671d93f

Please sign in to comment.