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();
+ }
}
}