Skip to content

Commit

Permalink
Fix event handler GC collection
Browse files Browse the repository at this point in the history
  • Loading branch information
EliaSaSe committed May 5, 2020
1 parent 8082541 commit 742ee98
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions WcfWuRemoteService/WindowsService/WindowsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,20 @@ public class WindowsService : ServiceBase
private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private ServiceWorker _worker;
private readonly int shutdownTimeout = 10000;

private delegate bool EventHandler(CtrlType sig);

[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

/// <summary>
/// A reference to the event handler is required during the process life time.
/// This reference prevents GC collection.
/// "'CallbackOnCollectedDelegate' : A callback was made on a garbage collected delegate of type ...
/// ... delegates to unmanaged code ... must be kept alive by the managed application ..."
/// </summary>
private static EventHandler eventHandler;

private enum CtrlType
{
CtrlCEvent = 0,
Expand All @@ -61,7 +72,7 @@ static void Main(string[] args)
if (Environment.UserInteractive) // Run as console application
{
var shutdownEvent = new ManualResetEventSlim(false);
var handler = new EventHandler(sig =>
eventHandler = new EventHandler(sig =>
{
// https://docs.microsoft.com/en-us/windows/console/handlerroutine
Log.Info(@"Exiting process due event: " + sig.ToString());
Expand All @@ -74,7 +85,7 @@ static void Main(string[] args)
PrintBoilerplate();
Log.Debug("Starting in interactive mode.");

SetConsoleCtrlHandler(handler, true);
SetConsoleCtrlHandler(eventHandler, true);
service.OnStart(args);
shutdownEvent.Wait(); // Waiting shutdown event
}
Expand Down

0 comments on commit 742ee98

Please sign in to comment.