Delay process exit in ConsoleLifetime #1329

This commit is contained in:
Chris Ross (ASP.NET) 2018-04-12 10:07:44 -07:00
parent 30ffadfebf
commit 4e1ba2a6c7
2 changed files with 19 additions and 3 deletions

View File

@ -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.");
}
}
}

View File

@ -11,8 +11,10 @@ namespace Microsoft.Extensions.Hosting.Internal
/// <summary>
/// Listens for Ctrl+C or SIGTERM and initiates shutdown.
/// </summary>
public class ConsoleLifetime : IHostLifetime
public class ConsoleLifetime : IHostLifetime, IDisposable
{
private readonly ManualResetEvent _shutdownBlock = new ManualResetEvent(false);
public ConsoleLifetime(IOptions<ConsoleLifetimeOptions> 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();
}
}
}