在连续的lambda调用中未调用C#Lambda构造函数 [英] C# Lambda constructor not called in consecutive lambda calls

查看:120
本文介绍了在连续的lambda调用中未调用C#Lambda构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c#aws lambda类,其构造函数中包含一些代码.每次启动lambda方法本身时都会调用该方法(带有SNS消息),但是,我看不到构造函数被调用(添加了从cloudwatch观察的日志调用).构造函数仅在首次启动时被调用(在aws堆栈创建/更新之后).

I have a c# aws lambda class with some code in its constructor. The lambda method itself is getting called every time I initiate it (with an SNS message post), however, I cannot see the constructor getting called (added log calls to observe from cloudwatch). The constructor only gets called at first launch (after the aws stack creation/update).

这是预期的行为吗? aws是否以某种方式缓存我的lambda实例?

Is this an expected behaviour? Does aws somehow cache my lambda instances?

public class MyLambda
{
     public MyLambda()
     {
          Console.WriteLine("Hello from ctor");
     }

     // This is the method assigned in CloudFormation
     public bool Execute(SNSEvent snsEvent)
     {          
          Console.WriteLine("Lambda called");
          return true;
     }
}

这是cloudwatch日志中的结果; 第一次启动Lambda:

And here is the outcome in cloudwatch log; First time initiate Lambda:

Hello from ctor
Lambda called

第二次启动Lambda

And second time initiation of Lambda

Lambda called

推荐答案

AWS按此常见问题解答中>和官方文档.

AWS reuses the instances as described in this blog post, in the FAQ and the official documentation.

通常,实例会不时地被重用和替换.如果负载较高,则AWS将创建更多并发实例.因此,通常您的实例很可能被重用,但是当它们被回收时,您不能指望它. 当实例被重用时,构造函数将不会再被调用,因为在初始化过程中已经调用了该构造函数.

In general the instances are reused and replaced every now and then. If you have a higher load AWS will create more concurrent instances. So usually it's very likely that your instances get reused, but you cannot count on it as they get recycled. When the instance is reused than the constructor won't be called again as the constructor was already called during the initialization.

通常,对新实例的第一次调用非常慢,因为运行时会进行初始化,例如加载自身,类加载等并调用构造函数.由于Lambda已完全初始化,因此后续调用通常要快得多.但是,如果您有一段时间没有给Lambda打电话了,它也需要从其冻结"中进行一些预热.这仍然构成重用,因此不会再次调用构造函数.

Usually the first call to a new instance is quite slow, as the run-time does initialization like loading itself, class loading, etc and calling the constructor. The subsequent calls are usually much faster as the Lambda is already fully initialized. However, if you haven't called your Lambda for a while it needs some warm-up from its "freeze" as well. This still constitutes a reuse, so the constructor won't be called again.

这篇关于在连续的lambda调用中未调用C#Lambda构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆