Skip to content

Commit dd63c20

Browse files
committed
Improve concurrent stopping of hosted services
Initialize a task list to track asynchronous stopping tasks of hosted services in the `TelegramBot` namespace within `BotApp.cs`. Modify the stopping logic to add each `StopAsync` task to the list and log the start of the stopping process. Await all tasks concurrently using `Task.WhenAll(tasks)` to potentially reduce the overall stopping time and provide clearer logging information.
1 parent 024ef2d commit dd63c20

1 file changed

Lines changed: 5 additions & 2 deletions

File tree

Sources/TelegramBot/BotApp.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,12 +141,14 @@ public async Task StopAsync(CancellationToken cancellationToken = default)
141141
var hostApplicationLifetime = _serviceProvider.GetRequiredService<IHostApplicationLifetime>();
142142
hostApplicationLifetime.StopApplication();
143143
var hostedServices = _serviceProvider.GetServices<IHostedService>();
144+
List<Task> tasks = new List<Task>();
144145
foreach (var hostedService in hostedServices)
145146
{
146147
try
147148
{
148-
await hostedService.StopAsync(cancellationToken);
149-
_logger.LogInformation("Hosted service '{hostedService}' stopped.", hostedService.GetType().Name);
149+
var task = hostedService.StopAsync(cancellationToken);
150+
tasks.Add(task);
151+
_logger.LogInformation("Stopping '{hostedService}'...", hostedService.GetType().Name);
150152
}
151153
catch (Exception ex)
152154
{
@@ -155,6 +157,7 @@ public async Task StopAsync(CancellationToken cancellationToken = default)
155157
}
156158
_logger.LogInformation("Stopping bot updates...");
157159
_cancellationTokenSource.Cancel();
160+
await Task.WhenAll(tasks);
158161
}
159162

160163
/// <summary>

0 commit comments

Comments
 (0)