From 4e1ba2a6c75fdc2866791b63bb22ee34efe74441 Mon Sep 17 00:00:00 2001 From: "Chris Ross (ASP.NET)" Date: Thu, 12 Apr 2018 10:07:44 -0700 Subject: [PATCH] Delay process exit in ConsoleLifetime #1329 --- samples/GenericHostSample/MyServiceB.cs | 7 ++++++- .../Internal/ConsoleLifetime.cs | 15 +++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/samples/GenericHostSample/MyServiceB.cs b/samples/GenericHostSample/MyServiceB.cs index a143758b90..fbc231d1c1 100644 --- a/samples/GenericHostSample/MyServiceB.cs +++ b/samples/GenericHostSample/MyServiceB.cs @@ -5,7 +5,7 @@ using Microsoft.Extensions.Hosting; namespace GenericHostSample { - public class MyServiceB : IHostedService + public class MyServiceB : IHostedService, IDisposable { private bool _stopping; private Task _backgroundTask; @@ -38,5 +38,10 @@ namespace GenericHostSample await _backgroundTask; } } + + public void Dispose() + { + Console.WriteLine("MyServiceB is disposing."); + } } } diff --git a/src/Microsoft.Extensions.Hosting/Internal/ConsoleLifetime.cs b/src/Microsoft.Extensions.Hosting/Internal/ConsoleLifetime.cs index a5160589b3..1e34d72741 100644 --- a/src/Microsoft.Extensions.Hosting/Internal/ConsoleLifetime.cs +++ b/src/Microsoft.Extensions.Hosting/Internal/ConsoleLifetime.cs @@ -11,8 +11,10 @@ namespace Microsoft.Extensions.Hosting.Internal /// /// Listens for Ctrl+C or SIGTERM and initiates shutdown. /// - public class ConsoleLifetime : IHostLifetime + public class ConsoleLifetime : IHostLifetime, IDisposable { + private readonly ManualResetEvent _shutdownBlock = new ManualResetEvent(false); + public ConsoleLifetime(IOptions options, IHostingEnvironment environment, IApplicationLifetime applicationLifetime) { Options = options?.Value ?? throw new ArgumentNullException(nameof(options)); @@ -38,7 +40,11 @@ namespace Microsoft.Extensions.Hosting.Internal }); } - AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => ApplicationLifetime.StopApplication(); + AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => + { + ApplicationLifetime.StopApplication(); + _shutdownBlock.WaitOne(); + }; Console.CancelKeyPress += (sender, e) => { e.Cancel = true; @@ -54,5 +60,10 @@ namespace Microsoft.Extensions.Hosting.Internal // There's nothing to do here return Task.CompletedTask; } + + public void Dispose() + { + _shutdownBlock.Set(); + } } }