Azure-functions-host: How to detect host shutdown using CancellationToken (aka Graceful shutdown)

Created on 30 Mar 2019  路  3Comments  路  Source: Azure/azure-functions-host

Is your question related to a specific version? If so, please specify:

  • Azure Functions Runtime 2.0.12382
  • Azure Functions Core Tools 2.5.553
  • Azure Functions SDK 1.0.26

What language does your question apply to? (e.g. C#, JavaScript, Java, All)

C#

Question

I want to use the CancellationToken to safely perform the restart that takes place during the execution of the Function.

I wrote the following code and tried the behavior of CancellationToken, but it seemed that cancellation was not performed when Function Host shutdown.

public static class Function1
{
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        CancellationToken cancellationToken,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function start.");

        try
        {
            // simulate excessive cpu time process
            await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken);
        }
        catch (OperationCanceledException)
        {
            log.LogInformation("C# HTTP trigger function canceled.");

            return new BadRequestResult();
        }

        log.LogInformation("C# HTTP trigger function end.");

        return new OkResult();
    }
}

The following is the log when trying to restart from Azure Portal while Function is running.

image

It seems that forced shutdown is performed while executing Function. Not only restart but also deployment has the same result.

On the other hand, at Function Timeout, it was confirmed that CancellationToken was working.

image

Is there a way to run Graceful shutdown like WebJobs?

bug

All 3 comments

@alrod - can you help answer this question?

@shibayan the approach you're using is correct. We do depend on the shutdown signaling flowing from IIS so we can correctly signal that token, and that should be happening in that scenario.

Assigning this for investigation as it looks like a defect.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rati3l picture rati3l  路  3Comments

ahmelsayed picture ahmelsayed  路  4Comments

Alezis picture Alezis  路  4Comments

alaatm picture alaatm  路  4Comments

silencev picture silencev  路  4Comments