Lambda函数处理程序C#中的取消令牌

Kev*_*ith 8 c# amazon-web-services cancellation-token aws-lambda

C#中的AWS Lambda函数处理程序是否提供取消令牌?

我已经阅读了AWS网站上的文档(https://docs.aws.amazon.com/lambda/latest/dg/dotnet-programming-model-handler-types.html),但在任何提及取消的地方都看不到令牌。我还检查了ILambdaContext传递给执行方法的,但是那里什么也没有。

我以前使用过Azure Functions,它们只是将它作为本文所述的函数的另一个参数传递给了我:https : //docs.microsoft.com/zh-cn/azure/azure-functions/functions-dotnet-类别库#取消令牌

Sea*_*ish 9

答案是否定的,正如你所发现的。目前没有CancellationToken提供。

您可以使用ILambdaContext.RemainingTimeand制作自己的CancellationTokenSource

public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context)
{
    var cts = new CancellationTokenSource(context.RemainingTime);
    var myResult = await MyService.DoSomethingAsync(cts.Token);
}
Run Code Online (Sandbox Code Playgroud)

我不确定这会有多大好处,因为当剩余时间用完时,Lambda 会被冻结,所以您的代码不会有机会优雅地停止。也许您可以估计您的代码需要多少时间优雅地停止然后在剩余时间之前取消令牌,例如:

var gracefulStopTimeLimit = TimeSpan.FromSeconds(2);
var cts = new CancellationTokenSource(context.RemainingTime.Subtract(gracefulStopTimeLimit));
Run Code Online (Sandbox Code Playgroud)

  • 还是这样。以下是处理程序函数和上下文的当前文档:https://docs.aws.amazon.com/lambda/latest/dg/csharp-handler.html 和 https://docs.aws.amazon.com/lambda/最新/dg/csharp-context.html (6认同)