phil
phil

Reputation: 2189

What keeps the BackgroundService.ExecuteAsync method from completing?

I have just created a Worker Service using the standard Visual Studio template. In the Worker class if I remove the while (!stoppingToken.IsCancellationRequested){...} wrapper and run the app, ExecuteAsync never completes. If I add return to the end of the method, again it doesn't complete.

Can anyone explain what keeps the method alive?

I wonder why in the code below that ExecuteAsync doesn't just complete and tear down my FileSystemWatcher? I can just keep triggering the watcher until pressing Ctrl+C which cancels the token and stops the whole application.

protected override async Task ExecuteAsync(CancellationToken stoppingToken) =>
            await Task.Run(async () =>
            {
                try
                {
                    _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                    _watcher = new FileSystemWatcher(_settings.Value.FolderToWatch, "Transactions_????????.xml")
                    {
                        NotifyFilter = NotifyFilters.FileName
                    };
                    _watcher.Created += FileCreated;
                    _watcher.EnableRaisingEvents = true;

                    _logger.LogInformation("Monitoring folder '{watchedFolder}' for file drops...", _settings.Value.FolderToWatch);
                }
                catch (Exception e) when (False(() => _logger.LogCritical(e,"Fatal error.")))
                {
                    throw;
                }

            });

Upvotes: 0

Views: 1105

Answers (1)

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11163

A BackgroundService doesn't care if your ExecuteAsync method completes before shutdown. It only cares that your service stops before the server can stop.

I would suggest that you implement a job queue, add to the queue in your FileCreated method, and process the queue in your ExecuteAsync method. Returning when stoppingToken is cancelled. That way you can block the server shutdown until the current file change has been processed, or pass on the cancel token.

And don't forget to Dispose() your FileSystemWatcher.

Upvotes: 1

Related Questions