Enabling cancellationToken on NET6 Lambda (REST API Gateway)

3

Hi,

We have a REST (edge) API Gateway to invoke a .NET 6 lambda function and in which we have included CancellationToken in some endpoints. It seems CancellationToken does not get propagated, and we are not sure what we are missing.

Has anyone else faced this issue and could provide us some insights?

Thanks

1 個回答
1

Unfortunately, Lambda doesn't provide a CancellationToken (to my knowledge). It can, however, tell you the amount of time remaining before it gives up, which you can build a CancellationToken around. For example:

public async Task<Stream> Process(Stream input, ILambdaContext lambdaContext)
{
    var timeout = lambdaContext.RemainingTime.Subtract(TimeSpan.FromSeconds(5d));
    using var cts = new CancellationTokenSource(timeout);

    await my.Work(cts.Token);

    return Stream.Null;
}

When the RemainingTime has been reached, Lambda will abruptly shut everything down. There is seemingly no nice way to handle that. Since cancellation is mutual, you'll want to pad the timeout with a few seconds to shut down gracefully. I have arbitrarily selected 5 seconds, but your needs might be different.

When you use the Lambda to ASP.NET Core integration, this process is handled for you automatically and you can just add CancellationToken as a parameter to your action methods as normal.

AWS
Chris M
已回答 2 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南