Search code examples
c#.netazureazure-webjobsbackground-service

.Net Core Background service on Azure as WebJob not calling StopAsync


We have a Windows Service, written in .Net Framework, that we are looking at porting to .NET Core and a BackgroundService running in Azure.

I have created a boilerplate BackgroundService (Worker Service project template) and deployed this to Azure as a WebJob.

Our service maintains a connection to a 3rd party API while it is running, so i need to ensure that this connection is closed gracefully when the WebJob stops; whether that be stopping the WebJob in Azure, publishing an updated version via VS.

However what i have found is that when i stop the WebJob in Azure, the StopAsync method is not called; instead i get a ThreadAborted exception in the logs.

Is there a best practice way to gracefully shutdown BackgroundService when run as a WebJob?

Or should i even be using some other Azure toolset for this?


Solution

  • If this helps anyone, i solved this, thanks for the pointer @HarshithaVeeramalla-MT, at https://blog.amitapple.com/post/2014/05/webjobs-graceful-shutdown/#.YZNWEk5By3A and https://github.com/projectkudu/kudu/wiki/WebJobs#graceful-shutdown

        private string _shutdownFile;
    
    public Worker(ILogger<Worker> logger)
    {            
        _logger = logger;
    
        _shutdownFile = Environment.GetEnvironmentVariable("WEBJOBS_SHUTDOWN_FILE");
    
        if (!string.IsNullOrEmpty(_shutdownFile))
        {
            _logger.LogInformation($"WebJob WEBJOBS_SHUTDOWN_FILE Environment Variable: {_shutdownFile}");
    
            var fileSystemWatcher = new FileSystemWatcher(Path.GetDirectoryName(_shutdownFile));
            fileSystemWatcher.Created += OnChanged;
            fileSystemWatcher.Changed += OnChanged;
            fileSystemWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastWrite;
            fileSystemWatcher.IncludeSubdirectories = false;
            fileSystemWatcher.EnableRaisingEvents = true;
        }
        else
        {
            _logger.LogWarning($"WebJob WEBJOBS_SHUTDOWN_FILE Environment Variable not found");
        }            
    }
    
    private void OnChanged(object sender, FileSystemEventArgs e)
    {
        _logger.LogInformation($"Filechanged: {e.FullPath}");
        _logger.LogInformation($"WebShutDownFile: {_shutdownFile}");
    
        _logger.LogInformation($"FileName: {Path.GetFileName(_shutdownFile)}");
    
        if (e.FullPath.IndexOf(Path.GetFileName(_shutdownFile), StringComparison.OrdinalIgnoreCase) >= 0)
        {
            // Found the file mark this WebJob as finished
            _logger.LogInformation($"***WebJob shutdown file found - shutting down service***");
        }
    }