diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/tests/WindowsServiceLifetimeTests.cs b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/tests/WindowsServiceLifetimeTests.cs index f275b47d709212..27a56fca3d5102 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/tests/WindowsServiceLifetimeTests.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/tests/WindowsServiceLifetimeTests.cs @@ -171,7 +171,7 @@ public void ServiceCanStopItself() serviceTester.Start(); // service will proceed to stopped without any error - serviceTester.WaitForStatus(ServiceControllerStatus.Stopped); + serviceTester.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.MaxValue); var status = serviceTester.QueryServiceStatus(); Assert.Equal(0, status.win32ExitCode); @@ -194,6 +194,8 @@ lifetime stopped """, logText); } + private static AutoResetEvent s_are = new AutoResetEvent(false); + [ConditionalFact(nameof(IsRemoteExecutorSupportedAndPrivilegedProcess))] public void ServiceSequenceIsCorrect() { @@ -208,8 +210,16 @@ public void ServiceSequenceIsCorrect() }) .Build(); + var windowsService = (LoggingWindowsServiceLifetime)host.Services.GetRequiredService(); + windowsService.WaitOnStop = true; + var applicationLifetime = host.Services.GetRequiredService(); - applicationLifetime.ApplicationStarted.Register(() => FileLogger.Log($"lifetime started")); + applicationLifetime.ApplicationStarted.Register(() => + { + FileLogger.Log($"lifetime started"); + s_are.Set(); + }); + applicationLifetime.ApplicationStopping.Register(() => FileLogger.Log($"lifetime stopping")); applicationLifetime.ApplicationStopped.Register(() => FileLogger.Log($"lifetime stopped")); @@ -260,6 +270,8 @@ public LoggingWindowsServiceLifetime(IHostEnvironment environment, IHostApplicat base(environment, applicationLifetime, loggerFactory, optionsAccessor) { } + public bool WaitOnStop { get; set; } + protected override void OnStart(string[] args) { FileLogger.Log("WindowsServiceLifetime.OnStart"); @@ -268,6 +280,10 @@ protected override void OnStart(string[] args) protected override void OnStop() { + if (WaitOnStop) + { + s_are.WaitOne(); + } FileLogger.Log("WindowsServiceLifetime.OnStop"); base.OnStop(); }