Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Exiting an Azure WebJob programmatically

4.00/5 (1 vote)
28 Sep 2023CPOL 5.7K  
Shows how to programmatically stop/exit a WebJob on Azure

Introduction

If you need your WebJob to run a task and exit, or if you need to conditionally exit it under certain scenarios, and you thought it’s just a matter of exiting the worker service’s ExecuteAsync method, you’d be wrong. Even after your worker code has stopped running, the parent host stays alive. The right way to exit your WebJob is to inject IHostApplicationLifetime into your worker, and then the last line of code in your ExecuteAsync would be a call to its StopApplication method.

Example code

C#
public Worker(ILogger<Worker> logger, IHostApplicationLifetime appLifeTime)
{
    _logger = logger;
    _appLifetime = appLifeTime;            
}
 
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    int runs = 0;
 
    while (!stoppingToken.IsCancellationRequested && runs++ < 3)
    {
        // do some task here   
        await Task.Delay(2000, stoppingToken);
    }
 
    _appLifetime.StopApplication();
}

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)