LandonC
LandonC

Reputation: 899

C# AWS Lambda and Thread.Sleep()

I have a foreach loop running inside an AWS lambda, with a Thread.Sleep(2000) to throttle execution. However, the code doesn't seem to pause: I've logged timestamps before and after its execution. Here's a simplified version of the method:

        private async Task<string> ExecuteAutoRetryRequest(string url)
        {
            string html = String.Empty;
            int numberOfRetry = 3;
            while (numberOfRetry > 0)
            {
                try
                {
                    html = await ExecuteGetRequest(url);
                    if (!string.IsNullOrEmpty(html) && !html.Contains("Access Denied"))
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    await LogException(ex.Message);
                }

                // Wait two seconds and try again
                Console.WriteLine(DateTime.Now.ToString());
                Thread.Sleep(2000);
                Console.WriteLine(DateTime.Now.ToString());
                numberOfRetry--;
            }

            return html;
        }

I call it like so var htmlSnapShotResult = await ExecuteAutoRetryRequest(url);

I'm sure this is something basic about how lambdas operate that I'm unaware of, but any help would be appreciated.

Upvotes: 1

Views: 1094

Answers (1)

LandonC
LandonC

Reputation: 899

Alexander's comment above is the correct answer: the following executes the pause correctly:

await Task.Delay(2000);

Upvotes: 2

Related Questions