Does AWS Lambda Function Handlers in C# provide a cancellation token?
I've read the documentation on AWS site (https://docs.aws.amazon.com/lambda/latest/dg/dotnet-programming-model-handler-types.html) but I can't see anywhere that mentions cancellation tokens. I've also inspected the ILambdaContext
that gets passed into the method of execution but there is nothing on there.
I've worked before with Azure Functions and they just pass it in as another argument to the functions as described in this article: https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#cancellation-tokens
The answer is no, as you've discovered. Currently no CancellationToken
is provided.
You could make your own using the ILambdaContext.RemainingTime
and CancellationTokenSource
:
public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context)
{
var cts = new CancellationTokenSource(context.RemainingTime);
var myResult = await MyService.DoSomethingAsync(cts.Token);
}
I'm not sure how much good this will do, since when the time remaining is gone the Lambda is frozen, so it's not like your code will have the chance to gracefully stop. Perhaps you can estimate how much time your code needs to gracefully stop and then cancel the token that long before the remaining time, something like:
var gracefulStopTimeLimit = TimeSpan.FromSeconds(2);
var cts = new CancellationTokenSource(context.RemainingTime.Subtract(gracefulStopTimeLimit));