From e27a8952cbd910e6db63790d5d8856f6ba9aa56d Mon Sep 17 00:00:00 2001
From: NextTurn <45985406+NextTurn@users.noreply.github.com>
Date: Tue, 25 Feb 2020 00:00:00 +0800
Subject: [PATCH] Replace thread with event
---
src/WinSW.Core/Util/ProcessHelper.cs | 37 +++++++++-------------------
src/WinSW.Core/WinSW.Core.csproj | 2 +-
src/WinSW/WrapperService.cs | 1 +
3 files changed, 14 insertions(+), 26 deletions(-)
diff --git a/src/WinSW.Core/Util/ProcessHelper.cs b/src/WinSW.Core/Util/ProcessHelper.cs
index a441a04..c5b537e 100644
--- a/src/WinSW.Core/Util/ProcessHelper.cs
+++ b/src/WinSW.Core/Util/ProcessHelper.cs
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
-using System.Threading;
using log4net;
using static WinSW.Native.ProcessApis;
@@ -194,32 +193,20 @@ namespace WinSW.Util
// monitor the completion of the process
if (callback != null)
{
- StartThread(() =>
+ processToStart.Exited += (_, _) =>
{
- processToStart.WaitForExit();
- callback(processToStart);
- });
- }
- }
+ try
+ {
+ callback(processToStart);
+ }
+ catch (Exception e)
+ {
+ Logger.Error("Thread failed unexpectedly", e);
+ }
+ };
- ///
- /// Starts a thread that protects the execution with a try/catch block.
- /// It appears that in .NET, unhandled exception in any thread causes the app to terminate
- /// http://msdn.microsoft.com/en-us/library/ms228965.aspx
- ///
- public static void StartThread(ThreadStart main)
- {
- new Thread(() =>
- {
- try
- {
- main();
- }
- catch (Exception e)
- {
- Logger.Error("Thread failed unexpectedly", e);
- }
- }).Start();
+ processToStart.EnableRaisingEvents = true;
+ }
}
}
diff --git a/src/WinSW.Core/WinSW.Core.csproj b/src/WinSW.Core/WinSW.Core.csproj
index 4bfa427..d47dd3d 100644
--- a/src/WinSW.Core/WinSW.Core.csproj
+++ b/src/WinSW.Core/WinSW.Core.csproj
@@ -2,7 +2,7 @@
net461;netcoreapp3.1
- latest
+ preview
enable
true
diff --git a/src/WinSW/WrapperService.cs b/src/WinSW/WrapperService.cs
index 4a8ce75..c44fc66 100644
--- a/src/WinSW/WrapperService.cs
+++ b/src/WinSW/WrapperService.cs
@@ -297,6 +297,7 @@ namespace WinSW
this.LogEvent("Stopping " + this.descriptor.Id);
Log.Info("Stopping " + this.descriptor.Id);
this.orderlyShutdown = true;
+ this.process.EnableRaisingEvents = false;
if (stopArguments is null)
{