-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Closed
Milestone
Description
Description
BackgroundService StopAsync never completes when called from a WPF project from Application.Exit event or Application.OnExit override. Not sure this is the right repo to open the issue so be patient with me.
To Reproduce
Steps to reproduce the behavior (sample project)
Relevant parts:
public partial class App : Application
{
private IHost _host;
public static IHostBuilder CreateHostBuilder() => new HostBuilder().ConfigureAppConfiguration((context, configurationBuilder) =>
{
configurationBuilder.AddEnvironmentVariables();
configurationBuilder.SetBasePath(context.HostingEnvironment.ContentRootPath);
});
public App()
{
_host = CreateHostBuilder().ConfigureServices((context, services) =>
{
services.AddHostedService<MyService>();
services.AddSingleton<MainWindow>();
}).Build();
}
private async void OnApplicationExit(object sender, ExitEventArgs e)
{
await _host.StopAsync();
_host.Dispose();
_host = null;
}
private async void OnApplicationStartup(object sender, StartupEventArgs e)
{
await _host.StartAsync();
var mainWindow = _host.Services.GetService<MainWindow>();
mainWindow.Show();
}
}public class MyService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(10, stoppingToken);
}
}
}Expected behavior
The StopAsync should complete or timeout.
Additional context
I think a deadlock occurs but I've no idea how to prevent it. I've tried to debug the BackgroundService class and the offending part is the Task.WhenAny included in StopAsync. I've also tried to wrap the call to StopAsync in a Task but the effect is the same.
Any suggestion is appreciated.
zyryanov